File Handling in Java

In Java, File I/O is handled by FileInputStream and FileOutputStream class provided by java.lang package.

Stream

Byte Streams - Java Byte Streams are used to perform input and output of 8-bit bytes.

Character Streams - Java Character Streams are used to perform 16-Bit Unicode Stream Operations. FileWriter and FileReader are used in character streams.

FileWriter is a subclass of FileOutputStream is helpful in wrapping file stream within character based object (Compared to Byte Oriented ). FileWriter writes two bytes at a time. For character based it’s suggested to use FileWriter to create stream, which creates an internal FileOutputStream to write bytes to the specified file.

Second step deals with BufferedWriter class which writes text to character output stream. And using the write() method, we can write to the file specified in the FileWriter.

package com.art.examples;

import java.io.*;
import java.util.Date;

public class FileHandling {
    public static final String FILENAME = "src/main/resources/filehandling.txt";

    public static void main(String[] args) {
        System.out.println("Writing to File");

        //Writing to File using Buffered Writer
        try (BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(FILENAME, true))){
            long currentTimeStamp = System.currentTimeMillis();

            bufferedWriter.write(currentTimeStamp + "- Hello World\n");
        }  catch (IOException e) {
            e.printStackTrace();
        }

        //Reading File using Buffered Reader
        try (BufferedReader bufferedReader = new BufferedReader(new FileReader(FILENAME))) {
            bufferedReader.lines().forEach(line->{
                System.out.println(line);
            });

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }


    }

}