Java Nio File Lines
[ Java java.nio.file.Files](#)
`Files.lines()` method is a static method introduced in Java 8, located in the `java.nio.file.Files` class. Its main purpose is to return the file contents as a stream of strings (`Stream`), where each string represents one line in the file.
### Method Definition
```java
public static Stream lines(Path path) throws IOException
```java
public static Stream lines(Path path, Charset cs) throws IOException
The method has two overloaded versions:
1. The first version reads the file using the default character set (UTF-8).
2. The second version allows specifying a custom character set.
### Core Features
#### 1. Lazy Evaluation
The `lines()` method returns a stream, which means it uses lazy evaluation. The entire file is not loaded into memory at once; instead, it is read on demand, making it particularly advantageous for handling large files.
#### 2. Automatic Resource Management
Once the stream operations are completedβwhether normally or due to an exceptionβthe underlying file resources are automatically closed. However, best practice still recommends using the try-with-resources statement to ensure proper resource release.
#### 3. Line Terminator Handling
The method automatically recognizes different line terminators:
* `n` (Unix/Linux)
* `rn` (Windows)
* `r` (Old Mac systems)
* * *
## Basic Usage
### Example 1: Simple File Reading
## Example
```java
import java.nio.file.*;
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 lines = Files.lines(path)) {
lines.forEach(System.out::println);
} catch (IOException e) {
e.printStackTrace();
}
}
}
### Example 2: Using a Specified Character Set
## Example
```java
try (Stream lines = Files.lines(path, StandardCharsets.ISO_8859_1)) {
lines.filter(line -> !line.isEmpty())
.forEach(System.out::println);
} catch (IOException e) {
e.printStackTrace();
}
* * *
## Advanced Usage
### 1. Combining with the Stream API
## Example
// Count non-empty lines
```java
long count = Files.lines(path)
.filter(line -> !line.trim().isEmpty())
.count();
// Find lines containing a specific word
```java
List targetLines = Files.lines(path)
.filter(line -> line.contains("important"))
.collect(Collectors.toList());
### 2. Parallel Processing
## Example
// Process file lines in parallel
```java
Files.lines(path)
.parallel()
.map(String::toUpperCase)
.forEachOrdered(System.out::println);
* * *
## Notes
1. **Resource Management**: Although the stream closes automatically, explicitly using try-with-resources is still recommended in complex stream operations.
2. **Performance Considerations**: For small files, `Files.readAllLines()` may be simpler; however, for large files, `lines()` is the better choice.
3. **Character Set Issues**: If the file encoding differs from the system's default encoding, always specify the correct character set to avoid garbled output.
4. **Exception Handling**: IO operations can throw exceptions, so they must be handled appropriately.
* * *
## Performance Comparison
| Method | Feature | Suitable Scenario |
| --- | --- | --- |
| `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
The `Files.lines()` method combines Java 8's Stream API with NIO's efficient file-handling capabilities, providing a modern and concise solution for file reading. It is especially well-suited for handling large files and performing complex line-level operations. Mastering this method can significantly improve the readability and efficiency of your file-processing code.
In real-world development, choosing between `lines()`, `readAllLines()`, or traditional IO methods based on file size, processing requirements, and performance needs will help you write optimal file-processing code.
[ Java java.nio.file.Files](#)
YouTip