Java Nio File
`java.nio.file.Files` is a utility class in the Java NIO (New I/O) package, located in the `java.nio.file` package.
`java.nio.file.Files` provides a series of static methods to operate 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 instances
* **Rich Functionality**: Provides various functions such as file reading/writing, attribute operations, directory traversal
* **Exception Handling**: Unified use of `IOException` for file operation exceptions
* **Works with Path**: Mainly used together with the `java.nio.file.Path` interface
* * *
## Common Methods Classification
**Note:** Many methods throw IOException, exception handling is required when using them.
Here are the commonly used methods of the java.nio.file.Files class:
| Method | Description |
| --- | --- |
| **File Operations** |
| `static Path copy(Path source, Path target, CopyOption... options)` | Copy file from source path to target path |
| `static Path move(Path source, Path target, CopyOption... options)` | Move or rename file |
| `static void delete(Path path)` | Delete file |
| `static boolean deleteIfExists(Path path)` | Delete if file exists |
| **File Attributes** |
| `static boolean exists(Path path, LinkOption... options)` | Check if file exists |
| `static boolean isDirectory(Path path, LinkOption... options)` | Check if path is a directory |
| `static boolean isRegularFile(Path path, LinkOption... options)` | Check if path is a regular file |
| `static boolean isReadable(Path path)` | Check if file is readable |
| `static boolean isWritable(Path path)` | Check if file is writable |
| `static boolean isExecutable(Path path)` | Check if file is executable |
| `static long size(Path path)` | Return file size (in bytes) |
| `static FileTime getLastModifiedTime(Path path, LinkOption... options)` | Get file last modified time |
| **File Content Operations** |
| `static byte[] readAllBytes(Path path)` | Read all bytes from file |
| `static List readAllLines(Path path)` | Read all lines from file |
| `static List readAllLines(Path path, Charset cs)` | Read all lines from file with specified charset |
| `static Stream lines(Path path)` | Return stream of lines in file |
| `static Stream lines(Path path, Charset cs)` | Return stream of lines in file with specified charset |
| `static Path write(Path path, byte[] bytes, OpenOption... options)` | Write bytes to file |
| `static Path write(Path path, Iterable lines, OpenOption... options)` | Write text lines to file |
| **Directory Operations** |
| `static Stream list(Path dir)` | List entries in directory |
| `static DirectoryStream newDirectoryStream(Path dir)` | Open directory stream |
| `static Path createDirectory(Path dir, FileAttribute... attrs)` | Create directory |
| `static Path createDirectories(Path dir, FileAttribute... attrs)` | Create directory (including all non-existent parent directories) |
| **Temporary Files/Directories** |
| `static Path createTempFile(Path dir, String prefix, String suffix, FileAttribute... attrs)` | Create temporary file |
| `static Path createTempDirectory(Path dir, String prefix, FileAttribute... attrs)` | Create temporary directory |
| **Others** |
| `static Path createFile(Path path, FileAttribute... attrs)` | Create new file |
| `static SeekableByteChannel newByteChannel(Path path, OpenOption... options)` | Open or create file, return seekable byte channel |
| `static InputStream newInputStream(Path path, OpenOption... options)` | Open file input stream |
| `static OutputStream newOutputStream(Path path, OpenOption... options)` | Open file output stream |
| `static BufferedReader newBufferedReader(Path path)` | Open buffered reader |
| `static BufferedWriter newBufferedWriter(Path path, OpenOption... options)` | Open buffered writer |
| `static String probeContentType(Path path)` | Probe file content type |
### 1. File Operations
#### File Reading and Writing
## Example
// Read all lines from file
List lines = Files.readAllLines(path);
// Write to file
Files.write(path, content.getBytes());
// Append to file
Files.write(path, content.getBytes(), StandardOpenOption.APPEND);
#### File Copy/Move/Delete
## Example
// Copy file
Files.copy(sourcePath, targetPath);
// Move/rename file
Files.move(sourcePath, targetPath);
// Delete file
Files.delete(path);
### 2. Directory Operations
#### Create Directory
## Example
// Create single-level directory
Files.createDirectory(path);
// Create multi-level directory
Files.createDirectories(path);
#### Directory Traversal
## Example
// Traverse directory
try(Stream paths = Files.list(directoryPath)){
paths.forEach(System.out::println);
}
// Recursively traverse directory
try(Stream paths = Files.walk(directoryPath)){
paths.forEach(System.out::println);
}
### 3. File Attribute Operations
#### Get File Attributes
## Example
// Check if file exists
boolean exists = Files.exists(path);
// Get file size
long size = Files.size(path);
// Get file last modified time
FileTime lastModifiedTime = Files.getLastModifiedTime(path);
#### Set File Attributes
## Example
// Set file last modified time
Files.setLastModifiedTime(path, FileTime.fromMillis(System.currentTimeMillis()));
// Set file permissions
Set perms = PosixFilePermissions.fromString("rwxr-x---");
Files.setPosixFilePermissions(path, perms);
* * *
## Advanced Features
### 1. File Search
## Example
// Find files with specific extension
try(Stream paths = Files.find(
directoryPath,
Integer.MAX_VALUE,
(path, attrs)-> path.toString().endsWith(".txt"))){
paths.forEach(System.out::println);
}
### 2. Temporary File Operations
## Example
// Create temporary file
Path tempFile = Files.createTempFile("prefix", ".suffix");
// Create temporary directory
Path tempDir = Files.createTempDirectory("tempDir");
### 3. File Attribute Views
## Example
// Get file owner
UserPrincipal owner = Files.getOwner(path);
// Get file store 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());
}
### 2. Resource Cleanup
## Example
try(Stream lines = Files.lines(path)){
lines.forEach(System.out::println);
}// Auto-close stream
### 3. Performance Considerations
* For large files, use buffered streams (`Files.newBufferedReader`/`Files.newBufferedWriter`)
* Consider using `Files.walk` instead of recursive calls for batch operations
* 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 | Unified use of IOException | Multiple exception types |
| Richness of Functionality | Richer functionality | Basic functionality |
| Symbolic Link Handling | Native support | Limited support |
| File Attribute Operations | More comprehensive | Limited |
Through the `Files` class, Java provides a more modern and powerful file operation API, and it is recommended to use it in new projects to replace the traditional `java.io.File` class.
YouTip