-
Notifications
You must be signed in to change notification settings - Fork 4
Java Reading text files with Files.readAllLines() API
Ramesh Fadatare edited this page Jul 11, 2019
·
1 revision
The Files.readAllLines() method reads all lines from a file. This method ensures that the file is closed when all bytes have been read or an exception is thrown. The bytes from the file are decoded into characters using the specified charset.
Note that this method reads the whole file into the memory; therefore, it may not be suitable for very large files.
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;
public class ReadTextFileEx2 {
public static void main(String[] args) throws IOException {
String fileName = "src/resources/sample.txt";
List<String> lines = Files.readAllLines(Paths.get(fileName),
StandardCharsets.UTF_8);
StringBuilder sb = new StringBuilder();
for (String line : lines) {
sb.append(line);
sb.append(System.lineSeparator());
}
System.out.println(sb);
}
}
The contents of the sample.txt file are read and printed to the console using the Files.readAllLines() method.