W3docs

How can I read a large text file line by line using Java?

To read a large text file line by line in Java, you can use a BufferedReader and pass it a FileReader object to read the file. Here's an example of how you can do this:

To read a large text file line by line in Java, you can use a BufferedReader with Files.newBufferedReader() to read the file efficiently. Here's an example of how you can do this:


import java.io.BufferedReader;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;

public class Main {
  public static void main(String[] args) {
    // Set the file path
    String filePath = "C:\\folder\\file.txt";

    try (BufferedReader br = Files.newBufferedReader(Paths.get(filePath), StandardCharsets.UTF_8)) {
      // Read the file line by line
      String line;
      while ((line = br.readLine()) != null) {
        // Process the line
        System.out.println(line);
      }
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
}

This code will read the file line by line and print each line to the console. The BufferedReader class provides a convenient way to read a large file efficiently, as it reads the file in chunks and stores them in a buffer, rather than reading the file one character at a time.

Note that this example uses Files.newBufferedReader() with explicit UTF-8 encoding. Using try-with-resources ensures the reader is automatically closed, preventing resource leaks. If you need a different encoding, simply replace StandardCharsets.UTF_8 with your desired Charset.