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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
package com.kscodes.sampleproject; import java.io.File; import java.io.FileInputStream; import java.io.IOException; public class FileReadingFIS { /** * @param args */ public static void main(String[] args) { File file = new File("C:\\testFileForReading.txt"); StringBuffer sb = new StringBuffer(); try (FileInputStream fis = new FileInputStream(file)) { int content; while ((content = fis.read()) != -1) { sb.append((char) content); } } catch (IOException e) { e.printStackTrace(); } System.out.println("The contents of the file are ::"); System.out.println(sb.toString()); } } |
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
package com.kscodes.sampleproject; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; public class FileReadingBR { /** * @param args */ public static void main(String[] args) { StringBuffer sb = new StringBuffer(); try (FileReader fileReader = new FileReader("C:\\testFileForReading.txt"); BufferedReader br = new BufferedReader(fileReader)) { String line; while ((line = br.readLine()) != null) { sb.append(line); } } catch (IOException e) { e.printStackTrace(); } System.out.println("The contents of the file are ::"); System.out.println(sb.toString()); } } |