What is the method for reading a text file in Java?

In Java, the method of reading text files can be achieved using the FileInputStream and BufferedReader classes from the java.io package. Below is a simple example code:

import java.io.*;

public class ReadTextFile {
    public static void main(String[] args) {
        try {
            File file = new File("sample.txt");
            FileInputStream fis = new FileInputStream(file);
            BufferedReader br = new BufferedReader(new InputStreamReader(fis));
            
            String line;
            while ((line = br.readLine()) != null) {
                System.out.println(line);
            }
            
            br.close();
            fis.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

In the example above, we start by creating a File object to represent the text file we want to read. Then we use FileInputStream to open the file and create a BufferedReader object to read the file content line by line. Finally, we read the file content line by line using the readLine() method and output each line’s content on the console. Remember to close the file input stream and buffered reader when finished.

bannerAds