Java Reading text files with FileReader

FileReader is a class used for reading character files. It uses system default character encoding. Since FileReader relies on system character settings, it is not recommended to use this class. We should use InputStreamReader instead.

Java Reading text files with FileReader

The code example reads text from the sample.txt file.
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class ReadTextFileExample {

    public static void main(String[] args) throws IOException {
        
        String fileName = "src/resources/sample.txt";
        
        try (BufferedReader br = new BufferedReader(new FileReader(fileName))) {

            StringBuilder sb = new StringBuilder();

            String line;
            while ((line = br.readLine()) != null) {

                sb.append(line);

                if (line != null) {
                    sb.append(System.lineSeparator());
                }
            }
            
            System.out.println(sb);
        }
    }
}
In the fileName variable, we store the path to the file.
String fileName = "src/resources/sample.txt";
The FileReader takes the file name as a parameter. The FileReader is passed to the BufferedReader, which buffers read operations for better performance. This is a try-with-resources statement which ensures that the resource (the buffered reader) is closed at the end of the statement.
try (BufferedReader br = new BufferedReader(new FileReader(fileName))) {
Printing lines to the console consumes a lot of resources. Therefore, we use the StringBuilder to build the output string and print it in one operation. The System.lineSeparator() returns the system-dependent line separator string.
StringBuilder sb = new StringBuilder();

String line;
while ((line = br.readLine()) != null) {

    sb.append(line);

    if (line != null) {
        sb.append(System.lineSeparator());
    }
}

System.out.println(sb);



Comments