The java.nio.file.Files.lines()
method is a Java NIO method used to read the contents of a file line by line. The code snippet will read the file from the specified filePath
and print each line to the console. The Files.lines()
method returns a Stream
of strings, and we use Stream’s forEach
method to print each line.
Note that we are using a try-with-resources
statement which will automatically close the stream after we are done with it, it’s a good practice to always close streams to free-up system resources.
Here’s a basic example of how you can use it.
package org.kodejava.io;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.io.IOException;
import java.util.stream.Stream;
public class ReadFile {
public static void main(String[] args) {
// replace with your file path
String filePath = "/Users/wayan/lipsum.txt";
// read file into stream, try-with-resources
try (Stream<String> stream = Files.lines(Paths.get(filePath))) {
stream.map(String::trim)
.forEach(System.out::println);
} catch (IOException e) {
e.printStackTrace();
}
}
}
The Files.lines()
method, along with other Java I/O and NIO methods, provide several important benefits and features:
- Memory Efficiency: This method reads the file line by line lazily, which means it doesn’t load the entire content of the file into memory. This is particularly useful when dealing with large files that could potentially exhaust system memory.
- Stream API Integration: The method returns a
Stream<String>
, it can naturally integrate with Java Stream API. This allows you to take advantage of powerful functions provided by Stream API such as filtering, mapping, reduction, etc., to process the file data effectively. - Readability: Using
Files.lines()
with atry-with-resources
construct results in more compact and readable code compared to older methods such asBufferedReader
. Thetry-with-resources
statement ensures that each resource is closed at the end of the statement, which can simplify cleanup code and avoid resource leaks. - Exceptions Handling: I/O operations can generally throw
IOException
which are checked Exceptions in Java. UsingFiles.lines()
within atry-with-resources
statement ensures that any underlying resources are closed properly, even in the event of an Exception. - Parallel Processing: Since
Files.lines()
method returns aStream<String>
, you can convert this stream into a parallel stream if you want to process the file with multithreading.
Remember, like with many programming choices, whether to use Files.lines()
or another method depends on the specific needs and constraints of your project.