Java NIO Files Class
java.nio.file.Filesis a utility class in the Java NIO (New I/O) package, located in thejava.nio.filepackage.
java.nio.file.FilesIt provides a series of static methods to operate on files and directories in the file system, greatly simplifying file I/O operations.
Main Features
- Static methods: All methods are static, no need to create an instance
- Rich functionality: Provides various functions such as file reading/writing, attribute operations, directory traversal, etc.
- Exception handling: Uniformly uses
IOExceptionto handle file operation exceptions - Works with Path: Mainly used with the
java.nio.file.Pathinterface
Classification of Common Methods
Note:Many methods throw IOException, so exception handling is required when using them.
The following are common methods of the java.nio.file.Files class:
1. File Operations
File Reading/Writing
Example
// Read all lines of a file
List<String> lines = Files.readAllLines(path);
// Write to a file
Files.write(path, content.getBytes());
// Append write
Files.write(path, content.getBytes(), StandardOpenOption.APPEND);
List<String> lines = Files.readAllLines(path);
// Write to a file
Files.write(path, content.getBytes());
// Append write
Files.write(path, content.getBytes(), StandardOpenOption.APPEND);
File Copy/Move/Delete
Example
// Copy a file
Files.copy(sourcePath, targetPath);
// Move/rename a file
Files.move(sourcePath, targetPath);
// Delete a file
Files.delete(path);
Files.copy(sourcePath, targetPath);
// Move/rename a file
Files.move(sourcePath, targetPath);
// Delete a file
Files.delete(path);
2. Directory Operations
Creating Directories
Example
// Create a single-level directory
Files.createDirectory(path);
// Create a multi-level directory
Files.createDirectories(path);
Files.createDirectory(path);
// Create a multi-level directory
Files.createDirectories(path);
Directory Traversal
Example
// Traverse a directory
try (Stream<Path> paths = Files.list(directoryPath)) {
paths.forEach(System.out::println);
}
// Recursively traverse a directory
try (Stream<Path> paths = Files.walk(directoryPath)) {
paths.forEach(System.out::println);
}
try (Stream<Path> paths = Files.list(directoryPath)) {
paths.forEach(System.out::println);
}
// Recursively traverse a directory
try (Stream<Path> paths = Files.walk(directoryPath)) {
paths.forEach(System.out::println);
}
3. File Attribute Operations
Getting File Attributes
Example
// Check if a file exists
boolean exists = Files.exists(path);
// Get the file size
long size = Files.size(path);
// Get the file's last modified time
FileTime lastModifiedTime = Files.getLastModifiedTime(path);
boolean exists = Files.exists(path);
// Get the file size
long size = Files.size(path);
// Get the file's last modified time
FileTime lastModifiedTime = Files.getLastModifiedTime(path);
Setting File Attributes
Example
// Set the file's last modified time
Files.setLastModifiedTime(path, FileTime.fromMillis(System.currentTimeMillis()));
// Set file permissions
Set<PosixFilePermission> perms = PosixFilePermissions.fromString("rwxr-x---");
Files.setPosixFilePermissions(path, perms);
Files.setLastModifiedTime(path, FileTime.fromMillis(System.currentTimeMillis()));
// Set file permissions
Set<PosixFilePermission> perms = PosixFilePermissions.fromString("rwxr-x---");
Files.setPosixFilePermissions(path, perms);
Advanced Features
1. File Searching
Example
// Find files with a specific extension
try (Stream<Path> paths = Files.find(
directoryPath,
Integer.MAX_VALUE,
(path, attrs) -> path.toString().endsWith(".txt"))) {
paths.forEach(System.out::println);
}
try (Stream<Path> paths = Files.find(
directoryPath,
Integer.MAX_VALUE,
(path, attrs) -> path.toString().endsWith(".txt"))) {
paths.forEach(System.out::println);
}
2. Temporary File Operations
Example
// Create a temporary file
Path tempFile = Files.createTempFile("prefix", ".suffix");
// Create a temporary directory
Path tempDir = Files.createTempDirectory("tempDir");
Path tempFile = Files.createTempFile("prefix", ".suffix");
// Create a temporary directory
Path tempDir = Files.createTempDirectory("tempDir");
3. File Attribute Views
Example
// Get the file owner
UserPrincipal owner = Files.getOwner(path);
// Get file storage information
FileStore store = Files.getFileStore(path);
UserPrincipal owner = Files.getOwner(path);
// Get file storage information
FileStore store = Files.getFileStore(path);
Best Practices
1. Exception Handling
Example
try {
Files.copy(sourcePath, targetPath, StandardCopyOption.REPLACE_EXISTING);
} catch (IOException e) {
System.err.println("File operation failed: " + e.getMessage());
}
Files.copy(sourcePath, targetPath, StandardCopyOption.REPLACE_EXISTING);
} catch (IOException e) {
System.err.println("File operation failed: " + e.getMessage());
}
2. Resource Cleanup
Example
try (Stream<String> lines = Files.lines(path)) {
lines.forEach(System.out::println);
} // Automatically close the stream
lines.forEach(System.out::println);
} // Automatically close the stream
3. Performance Considerations
- For large files, use buffered streams (
Files.newBufferedReader/Files.newBufferedWriter) - For batch operations, consider using
Files.walkinstead of recursive calls - Frequently accessed attributes can be cached
Comparison with Traditional I/O
| Feature | Files Class (NIO) | Traditional I/O (java.io) |
|---|---|---|
| Method Type | Static methods | Instance methods |
| Path Representation | Uses Path interface | Uses File class |
| Exception Handling | Uses IOException uniformly | Multiple exception types |
| Feature Richness | Richer functionality | Basic functionality |
| Symbolic Link Handling | Native support | Limited support |
| File Attribute Operations | More comprehensive | Limited |
Through theFilesclass, Java provides a more modern and powerful file operation API. It is recommended to use it in new projects to replace the traditionaljava.io.Fileclass.