Home » Java » Read files in java

Read files in java

This tutorial teaches you the basic steps of file reading in java. To do this here I used some pre-build classes call, BufferedReader, File, FileNotFoundException, and FileReader.

BufferedReader – This will read text from a character-input stream. In line 1.

File – This is the representation of the file or directory path of a file. In line 2.

FileNotFoundException – This is exception handling class and this exception is thrown during a failed attempt to open the file denoted by a specified pathname. In line 3.

FileReader – This return data in a file in byte format. In line 4.

First, we have to catch the file. In line 5, “file_path” is the actual file path in your computer system. Then, we will create an instance of FileReader bypassing the file. In line 6. Then we have to read input-stream from the file. So, we create an instance of BufferedReader by using the fileReader. This shows in line 7.

The while loop will read each line and print stream in the CMD.

 import java.io.BufferedReader; //line 1
 import java.io.File; //line 2
 import java.io.FileNotFoundException; //line 3
 import java.io.FileReader; //line 4

public class ReadFile {
public static void main(String[] args) throws FileNotFoundException {

    File file = new File("file_path"); // line 5
    FileReader fileReader = new FileReader(file); //line 6
    BufferedReader buffuredReader = new BufferedReader(fileReader);//line 7
    String data = "";//line 8
    try {
        while((data = buffuredReader.readLine()) != null){//line 9
            System.out.println(data);//line 10
    } catch (Exception e) {
        e.printStackTrace();//line 11
Please follow us:

Leave a Reply

Your email address will not be published. Required fields are marked *