SoFunction
Updated on 2025-03-02

Detailed explanation of the operation of java file Path, Paths, Files

PathPathsandFilesIt is a core component in the Java NIO (New I/O) file processing system, which provides more traditionalMore flexible and efficient file operation methods.

1. Overview

With the introduction of NIO.2 (i.e. Java New I/O 2), file processing has been significantly improved.PathPathsandFilesThey are three key components in NIO.2 for file and directory operations:

  • Path: Represents the path in the file system, similar to the traditional, but more flexible and feature-rich.
  • Paths: A tool class that provides static methods for creatingPathExample.
  • Files: A practical tool class that provides a large number of static methods to perform various operations of files and directories, such as creation, deletion, copying, moving, reading and writing.

Compared with traditionalFileClass, NIO.2 provides better error handling, richer functions and support for different file systems.

2. Path interface

Overview

Pathis an interface located inIn the package, it is used to represent paths in the file system. It provides a platform-independent way to represent paths to files and directories and supports rich path operations.

Main functions and methods

The following isPathSome key methods and functions of the interface:

Path creation and parsing

  • Path resolve(String other): parses the given path string into a subpath of the current path.
  • Path resolve(Path other): Will the givenPathSubpath resolved to the current path.
  • Path relativize(Path other): Calculate the relative path from the current path to the given path.

Path information

  • String getFileName(): Returns the file name part in the path.
  • Path getParent(): Returns the parent path of the path.
  • Path getRoot(): Returns the root component of the path.
  • int getNameCount(): Returns the number of name elements in the path.
  • Path getName(int index): Returns the name element of the specified index.

Path conversion

  • Path toAbsolutePath(): Convert relative paths to absolute paths.
  • Path normalize(): Normalize the path and remove redundant name elements, such as"."and".."

Path comparison

  • boolean startsWith(String other): Determines whether the path starts with the given path string.
  • boolean endsWith(String other): Determines whether the path ends with the given path string.
  • boolean equals(Object other): Determine whether the two paths are equal.

Other methods

  • Iterator<Path> iterator(): Returns an iterator for iterating over the name element in the path.
  • String toString(): Returns the string representation of the path.
  • String toAbsolutePath().toString(): Returns the string representation of the absolute path.

Sample code

import ;
import ;
public class PathExample {
    public static void main(String[] args) {
        // Create a Path instance        Path path = ("src", "main", "java", "");
        // Get the file name        ("file name: " + ());
        // Get the parent path        ("Parent Path: " + ());
        // Get the root path        ("Root Path: " + ());
        // Standardized paths        Path normalizedPath = ();
        ("Normalized path: " + normalizedPath);
        // Convert to absolute path        Path absolutePath = ();
        ("Absolute Path: " + absolutePath);
        // parse subpath        Path resolvedPath = ("subdir/");
        ("Resolved path: " + resolvedPath);
        // Calculate relative paths        Path basePath = ("src/main");
        Path relativePath = (path);
        ("Relative Path: " + relativePath);
        // traverse elements in the path        ("Path element:");
        for (Path element : path) {
            (element);
        }
    }
}

Output example:

file name:
Parent path: src/main/java
Root path: null
Normalized path: src/main/java/
Absolute path: /Users/username/project/src/main/java/
Path after parsing: src/main/java//subdir/
Relative path: java/
Path element:
src
main
java

3. Paths

Overview

Pathsis a final class located inIn the package, static methods are provided for creatingPathExample. It simplifiesPathThe object creation process makes the code more concise and easy to read.

Create a Path instance

import ;
import ;
import ;
public class PathsExample {
    public static void main(String[] args) {
        // Create paths with multiple string fragments        Path path1 = ("C:", "Users", "Public", "Documents");
        ("Path 1: " + path1);
        // Create paths with a single string        Path path2 = ("/home/user/docs");
        ("Path 2: " + path2);
        // Create a path using relative path        Path path3 = ("src/main/java/");
        ("Path 3: " + path3);
        // Combined path fragments        Path basePath = ("/home/user");
        Path combinedPath = ("downloads/music");
        ("The path after combination: " + combinedPath);
    }
}

Output example:

Path 1: C:\Users\Public\Documents
Path 2: /home/user/docs
Path 3: src/main/java/
Combined path: /home/user/downloads/music

Things to note

  • (...)The method will automatically process the path separator according to the operating system without manually specifying it. For example, on Windows, it will be used\, it will be used on Unix/Linux/

4. Files Class

Overview

Filesis a final class located inIn the package, a large number of static methods are provided to perform various operations of files and directories. It is withPathThe interface is tightly integrated, providing a comparisonMore richer and more efficient functions.

Main functions and methods

FilesClass methods can be roughly divided into the following categories:

  • Creation of files and directories
  • Delete files and directories
  • Copy and move files and directories
  • Reading and writing of file contents
  • Getting and modifying file attributes
  • Directory traversal and search

1. Creation of files and directories

  • static Path createFile(Path path, FileAttribute<?>... attrs): Create a new file.
  • static Path createDirectory(Path dir, FileAttribute<?>... attrs): Create a new directory.
  • static Path createDirectories(Path dir, FileAttribute<?>... attrs): Recursively creates directories, including non-existent parent directories.

2. Delete files and directories

  • static void delete(Path path): Delete the specified file or directory. If the path is a directory, the directory must be empty.
  • static boolean deleteIfExists(Path path): Delete the specified file or directory, if it exists.

3. Copy and move files and directories

  • static Path copy(Path source, Path target, CopyOption... options): Copy files or directories.
  • static Path move(Path source, Path target, CopyOption... options): Move or rename files or directories.

4. Reading and writing file contents

  • static byte[] readAllBytes(Path path): Read all bytes of the file.
  • static List<String> readAllLines(Path path, Charset cs): Read file contents by line.
  • static Path write(Path path, byte[] bytes, OpenOption... options): Write the byte array to the file.
  • static Path write(Path path, Iterable<? extends CharSequence> lines, Charset cs, OpenOption... options): Write lines to the file.

5. Acquisition and modification of file attributes

  • static boolean exists(Path path, LinkOption... options): Check whether the path exists.
  • static boolean isDirectory(Path path, LinkOption... options): Determine whether the path is a directory.
  • static boolean isRegularFile(Path path, LinkOption... options): Determine whether the path is a regular file.
  • static long size(Path path): Get the file size in bytes.
  • static FileTime getLastModifiedTime(Path path, LinkOption... options): Get the last modification time of the file.
  • static Path setLastModifiedTime(Path path, FileTime time): Set the last modification time of the file.

6. Directory traversal and search

  • static DirectoryStream<Path> newDirectoryStream(Path dir, <? super Path> filter): Open a directory stream and iterate through files and subdirectories in the directory.
  • static Stream<Path> walk(Path start, FileVisitOption... options): Recursively traverse the directory tree.
  • static Stream<Path> list(Path dir): List the contents in the directory without recursion.

Sample code

Here are some common onesFilesExample of class methods:

Create files and directories

import .*;
import ;
public class FilesCreateExample {
    public static void main(String[] args) {
        Path directory = ("exampleDir");
        Path file = ("");
        try {
            // Create a directory            if (!(directory)) {
                (directory);
                ("Directory created: " + directory);
            }
            // Create a file            if (!(file)) {
                (file);
                ("File created: " + file);
            }
        } catch (IOException e) {
            ();
        }
    }
}

Write and read file contents

import .*;
import ;
import ;
public class FilesReadWriteExample {
    public static void main(String[] args) {
        Path file = ("exampleDir/");
        // Write byte array to file        String content = "Hello, Java NIO!";
        try {
            (file, (), );
            ("Data has been written to file");
        } catch (IOException e) {
            ();
        }
        // Read all bytes        try {
            byte[] data = (file);
            ("File content (byte): " + new String(data));
        } catch (IOException e) {
            ();
        }
        // Read file contents by line        try {
            List&lt;String&gt; lines = (file, );
            ("File content (Press Line):");
            for (String line : lines) {
                (line);
            }
        } catch (IOException e) {
            ();
        }
    }
}

Copy and move files

import .*;
import ;
public class FilesCopyMoveExample {
    public static void main(String[] args) {
        Path source = ("exampleDir/");
        Path targetCopy = ("exampleDir/");
        Path targetMove = ("exampleDir/");
        try {
            // Copy the file            (source, targetCopy, StandardCopyOption.REPLACE_EXISTING);
            ("The file has been copied to: " + targetCopy);
            // Move files            (source, targetMove, StandardCopyOption.REPLACE_EXISTING);
            ("File has been moved to: " + targetMove);
        } catch (IOException e) {
            ();
        }
    }
}

Delete files and directories

import .*;
import ;
public class FilesDeleteExample {
    public static void main(String[] args) {
        Path file = ("exampleDir/");
        Path directory = ("exampleDir");
        try {
            // Delete the file            if ((file)) {
                ("File deleted: " + file);
            }
            // Delete the directory (the directory must be empty)            if ((directory)) {
                ("Directed directory: " + directory);
            }
        } catch (IOException e) {
            ();
        }
    }
}

Traversing the contents of the directory

import .*;
import ;
public class FilesListDirectoryExample {
    public static void main(String[] args) {
        Path directory = ("exampleDir");
        try (DirectoryStream&lt;Path&gt; stream = (directory)) {
            ("Files in Directory:");
            for (Path entry : stream) {
                (());
            }
        } catch (IOException e) {
            ();
        }
    }
}

Get and set file properties

import .*;
import ;
import ;
public class FilesAttributesExample {
    public static void main(String[] args) {
        Path file = ("exampleDir/");
        try {
            // Get file size            long size = (file);
            ("File Size: " + size + " byte");
            // Get the last modification time            FileTime lastModifiedTime = (file);
            ("Last modified time: " + lastModifiedTime);
            // Set the last modified time to the current time            FileTime newTime = (());
            (file, newTime);
            ("Last modified time has been updated");
            // Check whether the file exists            boolean exists = (file);
            ("The file exists: " + exists);
            // Check whether it is a directory            boolean isDirectory = (file);
            ("Yes Directory: " + isDirectory);
            // Check whether it is a regular file            boolean isRegularFile = (file);
            ("It's a regular file: " + isRegularFile);
        } catch (IOException e) {
            ();
        }
    }
}

Things to note

  • Exception handling:MostFilesAll methods of the class will be thrownIOException, therefore, appropriate exception handling is required when using these methods.
  • Atomic operation: Certain methods (such as) Atomic operations can be performed to ensure the integrity of file operations.
  • Performance considerations: For large files or large files operations, consider using streaming methods (such asand) to improve performance and reduce memory consumption.

5. Coordinated use of Path, Paths and Files

These three components are usually used together to enable comprehensive operations on files and directories. The following is a comprehensive example showing how to use itPathPathsandFilesComplete common file operation tasks.

Comprehensive examples

import .*;
import ;
import ;
import ;
public class ComprehensiveFileOperations {
    public static void main(String[] args) {
        Path directory = ("comprehensiveExampleDir");
        Path file = ("");
        Path copyFile = ("");
        Path movedFile = ("");
        try {
            // 1. Create a directory            if (!(directory)) {
                (directory);
                ("Directory created: " + directory);
            }
            // 2. Create a file            if (!(file)) {
                (file);
                ("File created: " + file);
            }
            // 3. Write data to file            String content = "Hello, Comprehensive Java NIO!";
            (file, (StandardCharsets.UTF_8), );
            ("Data has been written to the file: " + file);
            // 4. Read the file content            List&lt;String&gt; lines = (file, StandardCharsets.UTF_8);
            ("File Content:");
            for (String line : lines) {
                (line);
            }
            // 5. Copy the file            (file, copyFile, StandardCopyOption.REPLACE_EXISTING);
            ("The file has been copied to: " + copyFile);
            // 6. Move files            (file, movedFile, StandardCopyOption.REPLACE_EXISTING);
            ("File has been moved to: " + movedFile);
            // 7. Get file properties            long size = (movedFile);
            FileTime lastModifiedTime = (movedFile);
            ("File Size: " + size + " byte");
            ("Last modified time: " + lastModifiedTime);
            // 8. Traverse files in the directory            ("Files in Directory:");
            try (DirectoryStream&lt;Path&gt; stream = (directory)) {
                for (Path entry : stream) {
                    (());
                }
            }
            // 9. Delete files and directories            (copyFile);
            ("The copied file has been deleted: " + copyFile);
            (movedFile);
            ("Mobile file has been deleted: " + movedFile);
            (directory);
            ("Directed directory: " + directory);
        } catch (IOException e) {
            ();
        }
    }
}

Example of run result:

Directory created: comprehensiveExampleDir
File created: comprehensiveExampleDir/
Data has been written to file: comprehensiveExampleDir/
File content:
Hello, Comprehensive Java NIO!
The file has been copied to: comprehensiveExampleDir/
The file has been moved to: comprehensiveExampleDir/
File size: 31 bytes
Last modified time: 2024-04-27T10:15:30Z
Files in the directory:


The copied file has been deleted: comprehensiveExampleDir/
Moved file has been deleted: comprehensiveExampleDir/
Directory deleted: comprehensiveExampleDir

explain

  • Create directories and files:useandMethods to create directories and files.
  • Write and read files:useWrite strings to file, useRead file content.
  • Copy and move files:useCopy the file and useMove the file.
  • Get file properties:useandGet the file size and last modification time.
  • Traversal Directory:useTransfer the files in the directory.
  • Delete files and directories:useDelete files and directories.

6. Advanced features and best practices

1. Use file filters

Methods support the use of filters to filter files in directories. For example, only list.txtdocument:

import .*;
import ;
public class FilesFilterExample {
    public static void main(String[] args) {
        Path directory = ("exampleDir");
        try (DirectoryStream&lt;Path&gt; stream = (directory, "*.txt")) {
            ("The .txt file in the directory:");
            for (Path entry : stream) {
                (());
            }
        } catch (IOException e) {
            ();
        }
    }
}

2. Use the file traverser

For complex directory traversals, you can useCombination of methodsFileVisitorInterface, implements custom traversal logic. For example, find all the.javadocument:

import .*;
import ;
import ;
public class FilesWalkFileTreeExample {
    public static void main(String[] args) {
        Path startPath = ("src");
        try {
            (startPath, new SimpleFileVisitor&lt;Path&gt;() {
                @Override
                public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                    if (().endsWith(".java")) {
                        ("Finding Java File: " + file);
                    }
                    return ;
                }
            });
        } catch (IOException e) {
            ();
        }
    }
}

3. Asynchronous file operation

AlthoughFilesThe class mainly provides synchronous methods, but combines Java NIO asynchronous channels (such asAsynchronousFileChannel), can realize asynchronous file operation and improve performance.

import .*;
import .*;
import ;
import ;
import ;
public class AsynchronousFileExample {
    public static void main(String[] args) {
        Path file = ("");
        try (AsynchronousFileChannel asyncChannel = (file, , )) {
            String content = "Asynchronous File Writing in Java NIO.";
            ByteBuffer buffer = (());
            Future&lt;Integer&gt; operation = (buffer, 0);
            while (!()) {
                ("Writing to a file...");
                (100);
            }
            ("Writing is completed, number of bytes written: " + ());
        } catch (IOException | InterruptedException e) {
            ();
        }
    }
}

4. Handle file system differences

NIO.2 supports different types of file systems (such as local file systems, ZIP file systems, etc.). Can be usedFileSystemClasses and related methods to handle different file systems.

import .*;
import ;
public class ZipFileSystemExample {
    public static void main(String[] args) {
        Path zipPath = ("");
        try (FileSystem zipFs = (zipPath, null)) {
            Path internalPath = ("/");
            (internalPath, "Content writing to ZIP file".getBytes(), );
            ("File has been written to ZIP file");
        } catch (IOException e) {
            ();
        }
    }
}

5. Error handling and resource management

  • Exception handling: Try to use specific exception types, such asNoSuchFileExceptionDirectoryNotEmptyExceptionetc. to handle errors more accurately.
  • Resource Management: Use the try-with-resources statement to automatically close streams and directory streams to avoid resource leakage.
import .*;
import ;
public class ResourceManagementExample {
    public static void main(String[] args) {
        Path file = ("exampleDir/");
        // Use try-with-resources to read file content        try (BufferedReader reader = (file, StandardCharsets.UTF_8)) {
            String line;
            while ((line = ()) != null) {
                (line);
            }
        } catch (IOException e) {
            ();
        }
    }
}

6. Performance optimization

  • Batch operation: Try to read or write data in batches to reduce the number of I/O operations.
  • Buffered stream: Use buffered streams (such asBufferedReaderandBufferedWriter) Improve read and write performance.
  • Parallel processing: For large-scale file operations, parallel processing can be considered, such as using multithreading or parallel streaming.

7. Summary

PathPathsandFilesIt is the core component in Java NIO.2 that handles file and directory operations, providing a more traditionalMore modern, flexible and efficient functions. Here are their main features and best use scenarios:

  • Path

    • Represents paths in the file system and provides rich path operation methods.
    • Different fromString, provides platform-independent path processing.
  • Paths

    • Provide static methodsget, simplifyPathThe creation process of objects.
    • Make the code more concise and easy to read.
  • Files

    • Provides a large number of static methods to perform various operations of files and directories, such as creation, deletion, copying, moving, reading, writing, etc.
    • andPathTightly integrated, supporting advanced file operations and attribute management.

Best Practices

  • Preferred use of NIO.2 classes: In new projects, priority is givenPathPathsandFiles, not, for better performance and more features.
  • Use try-with-resources: Ensure that all streams and resources are correctly closed after use to avoid resource leakage.
  • Handle specific exceptions: Try to catch and deal with specific exception types so as to better deal with different error situations.
  • Optimize performance: For large or large-scale file operations, consider using buffered streams, batch operations, or parallel processing to improve performance.
  • Utilize file filtering and traverser:useDirectoryStreamandFileVisitorImplement efficient file filtering and directory traversal.
  • Keep path immutabilityPathObjects are immutable, which contributes to thread safety and code robustness.

Through full understanding and applicationPathPathsandFiles, can efficiently handle various file and directory operation tasks in Java applications, improving the maintainability and performance of the code.

This is the article about Java file operations (Path, Paths, Files) that ends with this article. For more related Java file operations, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!