Java java.nio.file.Files.lines() Method
Files.lines() method is a static method introduced in Java 8, located in the java.nio.file.Files class. Its main function is to return the file content as a stream of strings (Stream), where each string represents a line in the file.
Method Definition
public
static
Stream
<
String
lines
(Path path
)
throws
IOException
public
static
Stream
<
String
lines
(Path path, Charset cs
)
throws
IOException
The method has two overloaded versions:
- The first version reads the file using the default charset (UTF-8)
- The second version allows specifying the 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 normally or 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 released correctly.
3. Line terminator handling
The method automatically recognizes different line terminators:
\n(Unix/Linux)\r\n(Windows)\r(legacy Mac)
Basic Usage
Example 1: Simple file reading
Example
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
<
String
lines
=Files.
lines
(
path
)
)
{
lines.
forEach
(
System
.
out
::
println
)
;
}
catch
(
IOException
e
)
{
e.
printStackTrace
(
)
;
}
}
}
Example 2: Use a specified charset
Example
try
(
Stream
<
String
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. Combine with the Stream API
Example
// Count non-empty lines
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
// Process file lines in parallel
Files.
lines
(
path
)
.
parallel
(
)
.
map
(
String
::
toUpperCase
)
.
forEachOrdered
(
System
.
out
::
println
)
;
Notes
-
Resource management: Although the stream auto-closes, in complex stream operations, explicit use of try-with-resources is still recommended.
-
Performance considerations: For small files,
Files.readAllLines()may be simpler; but for large files,lines()is the 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 | Feature | Applicable scenarios |
|---|---|---|
Files.lines() |
Lazy loading, high memory efficiency | Large file processing |
Files.readAllLines() |
Load all lines into memory at once | Small file processing |
BufferedReader.readLine() |
Traditional approach, manual control | When fine-grained control is needed |
Summary
Files.lines() method combines Java 8's Stream API and NIO's efficient file handling capabilities, providing a modern and concise solution for file reading. It is especially 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 practical development, based on file size, processing needs, and performance requirements, reasonably choose lines(), readAllLines() or traditional IO methods to write optimal file-processing code.
Java java.nio.file.Files