Java read file Example
In this example we will show how to open and read a file in Java. There are many ways to do this, but we will show two of them. For this example, we will read the contents of a text file named“test_file.txt”.
1. Read a file using BufferedReader
This is the most commonly-used method in order to read a file in Java.BufferedReader reads text from a character-input stream, buffering the characters for the more efficient reading of characters, arrays, and lines.
Create a java class namedReadFileBufferedReader.java with the following code:
ReadFileBufferedReader.java
package com.javacodegeeks.javaio.readfile;import java.io.BufferedReader;import java.io.FileReader;import java.io.IOException;public class ReadFileBufferedReader {private static String filepath = "/home/konstantina/test_file.txt";public static void main(String[] args) {BufferedReader br;String curline;try {br = new BufferedReader(new FileReader(filepath));while ((curline = br.readLine()) != null) {System.out.println(curline);}br.close();} catch (IOException e) {e.printStackTrace();}}}In this case, we used the classFileReader along withBufferedReader.FileReader needs the file’s name and path so as to open the file. TheBufferedReader class provides a method namedreadLine() so as to read each line of the file. There is a while loop which is executed tillreadLine() reaches the end of the file.
If we run the above code, we will see the contents of the file“test_file.txt”.
- Output:
This is a test file.Read file exampleprovided byexamples.javacodegeeks.com2. Read a file using FileInputStream
This is another way of reading a file.FileInputStream reads streams of raw bytes from a file. So, we need to convert those bytes to characters in order to display the contents of the file to the screen.
Create a java class namedReadFileInputStream.java with the following code:
ReadFileInputStream.java
package com.javacodegeeks.javaio.readfile;import java.io.File;import java.io.FileInputStream;import java.io.IOException;public class ReadFileInputStream {private static String filepath = "/home/konstantina/test_file.txt";public static void main(String[] args) {try {File file = new File(filepath);FileInputStream in = new FileInputStream(file);System.out.println("Total bytes to read from file : "+ in.available());int i;StringBuffer buf = new StringBuffer("");while ((i = in.read()) != -1) {// convert byte to char and append to StringBufferbuf.append((char) i);}in.close();System.out.println("File contents :");System.out.println(buf);} catch (IOException e) {e.printStackTrace();}}}If we run the above code, we will have the following results:
- Output:
Total bytes to read from file : 78File contents :This is a test file.Read file exampleprovided byexamples.javacodegeeks.com3. Download the source code
You can download the source code of this example from here:ReadFileExample.zip

Thank you!
We will contact you soon.




