What is the actual difference between java Files.lines and Files.newBufferedReader().lines in Java?

1.3k Views Asked by At

Both two method will return stream of data, Is there any different between these two methods? If it's Which way is more suitable to read the large files?

1

There are 1 best solutions below

3
Sascha On

The difference is, Files.lines gives you a BaseStream which you have to close to prevent resource leakage. Files.newBufferedReader on the other hand gives you a Reader which you have to close. So in the end Files.lines is a shortcut if you are only interested in the lines as a Stream. Otherwise it behaves pretty similar:

    Path path=Paths.get("file.txt");

    try(Stream<String> stream=Files.lines(path))
    {
        stream.forEach(System.out::println);
    }
    
    try(BufferedReader reader=Files.newBufferedReader(path))
    {
        reader.lines().forEach(System.out::println);
    }

As the Java 9 Javadoc for Files.lines states in the "Implementation Note", it is optimized for parallelization for the StandardCharsets UTF-8, US-ASCII and ISO-8859-1. And thus to prefer for larger files with one of those encodings.