Open In App

java.nio.file package

Last Updated : 08 Nov, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

The java.nio.file package, introduced in Java 7 (NIO.2), provides a modern and efficient API for working with files, directories, and file systems, replacing many limitations of the old java.io.File class.

  • Path Abstraction: Represents file and directory paths using the Path interface.
  • File Operations: Perform read, write, copy, move, and delete operations easily with the Files class.
  • File Monitoring: Watch directories for creation, deletion, or modification events using the Watch Service API.

Important Classes and Interfaces

Class / InterfaceDescription
Path (interface)Represents a file or directory path in a platform-independent way. Created using Paths.get() or FileSystem.getPath().
FileSystemRepresents a file system. Provides methods to access paths and file stores (via FileSystems.getDefault()).
FileSystemsFactory class for creating or accessing file systems.
PathsUtility class with static methods to create Path objects from strings or URIs.
FilesUtility class with static methods for file and directory operations like copy(), move(), delete(), exists(), and readAllBytes().
DirectoryStreamProvides lazy and efficient iteration over directory contents.
FileVisitor<T>Interface for traversing file trees, handling each file or directory visited.
SimpleFileVisitor<T>Convenience class that implements FileVisitor with default methods.
WatchServiceAllows monitoring of directory changes (including create, modify, and delete events).

Path and Paths in Java

The Path interface and Paths class were introduced in Java NIO.2 for platform-independent file path handling.

1. Path

Path is an interface that represents a file or directory path in the file system. It's the modern alternative to java.io.File.

Syntax:

Path path = Paths.get("example.txt");

Common Methods of Path Interface

Example:

Path path = Paths.get("data/report.txt");
System.out.println(path.getFileName()); // report.txt
System.out.println(path.getParent()); // data
System.out.println(path.toAbsolutePath()); // C:\Users\vishnu\project\data\report.txt

2. Paths

The Paths class in java.nio.file is a final utility class that provides static factory methods to create Path objects. It acts as a bridge between string or URI representations and the Path interface.

Path path = Paths.get("C:", "Users", "vishnu", "Documents", "file.txt");

File Operations in Files Class

The Files class in java.nio.file package provides utility methods for working with files and directories, like reading, writing, copying, moving, deleting and more. It’s a modern alternative to FileInputStream, FileOutputStream and java.io.File.

Create Files and Directories

Path path = Paths.get("data.txt");
Files.createFile(path); // This line is used to creates a new file


Path dirPath = Paths.get("myfolder");
Files.createDirectory(dirPath); // Creates a new directory

Copy Files

Files.copy(Paths.get("data1.txt"), Paths.get("data2.txt"), StandardCopyOption.REPLACE_EXISTING);

Delete Files

Files.delete(Paths.get("copy.txt")); // Throws exception if file doesn't exist
Files.deleteIfExists(Paths.get("copy.txt")); // Safe delete

Write to a File

Files.writeString(Paths.get("data.txt"), "Hello, NIO!");

Directory Traversal

java.nio.file package provides two powerful mechanisms for traversing directories:

1. Using DirectoryStream

It is used for iterating through the contents of a single directory.

Java
import java.io.IOException;
import java.nio.file.*;

public class DirectoryStreamExample {
    public static void main(String[] args)
        throws IOException
    {
        Path dir = Paths.get("myfolder");

        try (DirectoryStream<Path> stream
             = Files.newDirectoryStream(dir)) {
            for (Path file : stream) {
                System.out.println(file.getFileName());
            }
        }
    }
}

2. Using FileVisitor

It is used with Files.walkFileTree() for depth-first traversal of file trees.

Java
Files.walkFileTree(Paths.get("."), new SimpleFileVisitor<>() {
    @Override
    public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) {
        System.out.println("Visited: " + file);
        return FileVisitResult.CONTINUE;
    }
});

WatchService API (Monitoring File Changes)

The WatchService API in Java (introduced in Java 7) allows you to monitor a directory for file system changes such as:

  • File creation (ENTRY_CREATE)
  • File modification (ENTRY_MODIFY)
  • File deletion (ENTRY_DELETE)

Create the instance of WatchService

WatchService watchService = FileSystems.getDefault().newWatchService()

Steps to Implement

  • Create a WatchService instance.
  • Register the directory with event kinds (CREATE, DELETE, MODIFY).
  • Continuously poll for file system events.
  • Process each event and reset the key.

Example: to Watch a Directory for Changes in Java

Java
import java.io.IOException;
import java.nio.file.*;

public class FileData {
    public static void main(String[] args)
    {
        try {
            // Specify the directory which supposed to be watched
            Path directoryPath = Paths.get("./");

            // Create a WatchService
            WatchService watchService = FileSystems.getDefault().newWatchService();

            // Register the directory for specific events
            directoryPath.register(
                watchService,
                StandardWatchEventKinds.ENTRY_CREATE,
                StandardWatchEventKinds.ENTRY_DELETE,
                StandardWatchEventKinds.ENTRY_MODIFY);

            System.out.println("Watching directory: "+ directoryPath);

            // Infinite loop to continuously watch for events
            while (true) {
                WatchKey key = watchService.take();

                for (WatchEvent<?> event :
                     key.pollEvents()) {
                    // Handle the specific event
                    if (event.kind() == StandardWatchEventKinds.ENTRY_CREATE) {
                        System.out.println("File created: " + event.context());
                    }
                    else if (event.kind() == StandardWatchEventKinds.ENTRY_DELETE) {
                        System.out.println("File deleted: "+ event.context());
                    }
                    else if (event.kind()== StandardWatchEventKinds.ENTRY_MODIFY) {
                        System.out.println("File modified: "+ event.context());
                    }
                }

                // To receive further events, reset the key
                key.reset();
            }
        }
        catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }
    }
}

Explanation:

  • The above code monitors the current directory (./) for file changes using Java NIO's WatchService.
  • Creates a WatchService to detect file creation, deletion and modification events.
  • Registers the directory to watch for these specific event types.
  • Prints the directory being watched.
  • Runs an infinite loop to continuously detect and handle file events.
  • On each event, it identifies the type (create, delete, modify) and prints the affected file name.
  • Resets the watch key after processing events to keep listening.
  • Handles any IOException or InterruptedException with error output.

Article Tags :

Explore