Java java.nio.file.Files.lines()Method
Files.lines()The method is a static method introduced in Java 8, located in thejava.nio.file.Filesclass. Its main purpose is to return file content as a string stream (Stream<String>), where each string represents a line in the file.
Method Definition
public static Stream<String> lines(Path path, Charset cs) throws IOException
The method has two overloaded versions:
- The first version reads files using the default charset (UTF-8)
- The second version allows specifying a charset
Core Features
1. Lazy Evaluation
lines()The method returns a Stream, which means it is lazily evaluated. The file is not loaded entirely into memory at once, but read on demand, which is especially beneficial for processing large files.
2. Automatic Resource Management
When the stream operation completes (whether it ends normally or is interrupted by an exception), the stream automatically closes the underlying file resources. However, the best practice is still to use the try-with-resources statement to ensure resources are properly released.
3. Line Terminator Handling
The method automatically recognizes different line terminators:
\n(Unix/Linux)\r\n(Windows)\r(old Mac)
Basic Usage
Example 1: Simple File Reading
Example
import java.io.IOException;
import java.util.stream.Stream;
public class FilesLinesExample {
public static void main(String[] args) {
Path path = Paths.get("example.txt");
try (Stream<String> lines = Files.lines(path)) {
lines.forEach(System.out::println);
} catch (IOException e) {
e.printStackTrace();
}
}
}
Example 2: Using a Specified Charset
Example
lines.filter(line -> !line.isEmpty())
.forEach(System.out::println);
} catch (IOException e) {
e.printStackTrace();
}
Advanced Usage
1. Combining with Stream API
Example
long count = Files.lines(path)
.filter(line -> !line.trim().isEmpty())
.count();
// Find lines containing a specific word
List<String> targetLines = Files.lines(path)
.filter(line -> line.contains("important"))
.collect(Collectors.toList());
2. Parallel Processing
Example
Files.lines(path)
.parallel()
.map(String::toUpperCase)
.forEachOrdered(System.out::println);
Notes
Resource Management: Although the stream closes automatically, explicitly using try-with-resources is still recommended in complex stream operations.
Performance Considerations: For small files,
Files.readAllLines()may be simpler; but for large files,lines()is a better choice.Charset Issues: If the file encoding differs from the system default encoding, be sure to specify the correct charset; otherwise, garbled text may be read.
Exception Handling: IO operations may throw exceptions and need to be handled properly.
Performance Comparison
| Method | Features | Applicable Scenarios |
|---|---|---|
Files.lines() |
Lazy loading, high memory efficiency | Large file processing |
Files.readAllLines() |
Loads all lines into memory at once | Small file processing |
BufferedReader.readLine() |
Traditional approach, manual control | When fine-grained control is needed |
Summary
Files.lines()The method combines Java 8's Stream API with NIO's efficient file processing capabilities, providing a modern and concise solution for file reading. It is particularly suitable for processing large files and performing complex line-level operations. Mastering this method can significantly improve the readability and efficiency of file processing code.
In actual development, based on file size, processing requirements, and performance needs, reasonably chooselines()、readAllLines()or traditional IO methods to write optimal file processing code.
Java java.nio.file.Files