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.
Method 1 - using java.nio.Files
-
is an utility class, which has lot of static methods that operate on files, in the below example we are going to usejava.nio.Files method which returnsFiles.lines(Path) of Strings, each String represents a line in file. Alternatively we can useStream as well, which returnsFiles.readAllLines(Path) of Strings, where each String represents a line from input file.List
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
reads content of a file as a stream of characters from the file, and this class mainly intended for reading the data as text only.FileReader- It is possible to read one character at a time or an array of characters in each read method call, both examples are shown below.
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()
- We can also read an array of characters in one go, and in this example we are reading 1024 characters at a time and continuing until it reaches end of file.
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[])
Method 3 - using java.io.BufferedReader
expects anotherBufferedReader as an input argument and the actual I/O operations such as reading from source file will be delegated to this underlying Reader class.java.io.Reader- BufferedReader maintains a character array as a buffer in the memory to store chunks of characters data, so for any read request, it will return the data from the buffer as long as it has data and if it is empty then it reads the data from underlying source and fill the buffer. The default buffer size is 16KB, using this intermediate buffer it reduces number of I/O operations to the underlying source.
- BufferedReader comes handy if you want to read input from files or sockets or any other source and it is thread-safe (synchronized)
Files.newBufferedReader(Path)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()
Above examples source code can be found at