How to read a text file in Java

Java provides several APIs for reading text files, each suited to different needs. This article covers three approaches: Files.readString() and Files.readAllLines() from java.nio for concise one-liners, FileReader for character-stream reading, and BufferedReader for efficient line-by-line processing of larger files.

In order to follow below examples, create a text file (sample.txt) with below content.

Hello, it's a great day today!

Method 1 - using java.nio.Files

Java
public static void readFile() {
  try {
    Stream<String> lines = Files.lines(Path.of("/path/to/sample.txt"));
    lines.forEach(System.out::println);
  } catch (IOException ioException){
    ioException.printStackTrace();
  }
}

Method 2 - using java.io.FileReader

Java
public static void readFile() {
  File inputFile = new File("/path/to/sample.txt");
  try(FileReader fileReader = new FileReader(inputFile)) {
    int ch;
    // fileReader.read() will return -1 if there is nothing left to read
    while((ch = fileReader.read()) != -1) {
      System.out.print((char)ch);
    }
  } catch (Exception ex) {
    ex.printStackTrace();
  }
}

In the above code, fileReader.read() method returns the character that it read, and when it reached end of file it returns -1.

Java
public static void readFile() {
  try(FileReader fileReader = new FileReader("/path/to/sample.txt")) {
    StringBuilder sb = new StringBuilder();
    char[] text = new char[1024];
    int count;
    while((count = fileReader.read(text)) != -1) {
      sb.append(text, 0, count);
    }
    System.out.println(sb.toString());
  } catch(Exception e) {
    e.printStackTrace();
  }
}

In the above code, FileReader.read(char[]) reads specified number of characters into the character array and returns how many characters were read and filled, when it reached end of file it returns -1.

Method 3 - using java.io.BufferedReader

To obtain BufferedReader instance, we could also use this utility method Files.newBufferedReader(Path)
Java
public static void readFile() {
  try (BufferedReader br = new BufferedReader(new FileReader("/path/to/sample.txt"))) {
    String line;
    while((line = br.readLine()) != null) {
      System.out.println(line);
    }
  } catch (Exception ex) {
    ex.printStackTrace();
  }
}

In the above code, BufferedReader.readLine() method reads and returns one line at a time until it reaches end of file, and returns null when it reaches end of file.

Above examples source code can be found at GitHub link for Java code and JUnit tests can be found at GitHub link for Unit tests code

Similar Articles

  1. How to efficiently read large files in Java