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

Hello, it's a great day today!
using java.nio.Files 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(); } }
using java.io.FileReader 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.

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.

using java.io.BufferedReader
To obtain BufferedReader instance, we could also use this utility method
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