Reading file in java

Reading file in java can be done using either FileInputStream or BufferedReader.

Reading File in java using FileInputStream

The below code uses a FileInputStream to get access of the File and then read each character of the file.

We are using a StringBuffer to store all the contents of the file and then display it once the entire file is read.

We are using Java 7 try-with-resource feature (check Try-with-resources Statement – Java 7), hence we are not releasing the used FileInputStream resource.


Reading File in java using BufferedReader

The below code using BufferedReader and reads the file line by line.
Similar to above code, we are using the Java 7 try-with-resource feature.

Please note that in the try block we have 2 statements.
1st we have a FileReader intialized and then we have the BufferReader initialized.