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 usesIOExceptionto handle file operation exceptions
  • Works with Path: Mainly used with thejava.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:

Method Description
File Operations
static Path copy(Path source, Path target, CopyOption... options) Copies a file from the source path to the target path
static Path move(Path source, Path target, CopyOption... options) Moves or renames a file
static void delete(Path path) Deletes a file
static boolean deleteIfExists(Path path) Deletes a file if it exists
File Attributes
static boolean exists(Path path, LinkOption... options) Checks if a file exists
static boolean isDirectory(Path path, LinkOption... options) Checks if the path is a directory
static boolean isRegularFile(Path path, LinkOption... options) Checks if the path is a regular file
static boolean isReadable(Path path) Checks if a file is readable
static boolean isWritable(Path path) Checks if a file is writable
static boolean isExecutable(Path path) Checks if a file is executable
static long size(Path path) Returns the file size (bytes)
static FileTime getLastModifiedTime(Path path, LinkOption... options) Gets the file's last modified time
File Content Operations
static byte[] readAllBytes(Path path) Reads all bytes of a file
static List<String> readAllLines(Path path) Reads all lines of a file
static List<String> readAllLines(Path path, Charset cs) Reads all lines of a file using a specified charset
static Stream<String> lines(Path path) Returns a stream of lines in the file
static Stream<String> lines(Path path, Charset cs) Returns a stream of lines in the file using a specified charset
static Path write(Path path, byte[] bytes, OpenOption... options) Writes bytes to a file
static Path write(Path path, Iterable<? extends CharSequence> lines, OpenOption... options) Writes text lines to a file
Directory Operations
static Stream<Path> list(Path dir) Lists entries in a directory
static DirectoryStream<Path> newDirectoryStream(Path dir) Opens a directory stream
static Path createDirectory(Path dir, FileAttribute<?>... attrs) Creates a directory
static Path createDirectories(Path dir, FileAttribute<?>... attrs) Creates a directory (including all non-existent parent directories)
Temporary Files/Directories
static Path createTempFile(Path dir, String prefix, String suffix, FileAttribute<?>... attrs) Creates a temporary file
static Path createTempDirectory(Path dir, String prefix, FileAttribute<?>... attrs) Creates a temporary directory
Others
static Path createFile(Path path, FileAttribute<?>... attrs) Creates a new file
static SeekableByteChannel newByteChannel(Path path, OpenOption... options) Opens or creates a file, returning a seekable byte channel
static InputStream newInputStream(Path path, OpenOption... options) Opens a file input stream
static OutputStream newOutputStream(Path path, OpenOption... options) Opens a file output stream
static BufferedReader newBufferedReader(Path path) Opens a buffered reader
static BufferedWriter newBufferedWriter(Path path, OpenOption... options) Opens a buffered writer
static String probeContentType(Path path) Probes the content type of a file

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);

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);

2. Directory Operations

Creating Directories

Example

// Create a single-level directory
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);
}

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);

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);

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);
}

2. Temporary File Operations

Example

// Create a temporary file
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);

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<String> lines = Files.lines(path)) {
    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 usingFiles.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.

Other Extensions