In Java 7, Oracle introduced **NIO.2** (Non-blocking I/O) which replaced the old java.io.File class. By separating file operations into two utility structures—Path (representing where a file is) and Files (containing actual actions)—Java became much safer, faster, and more robust.
In this guide, we will look at how to create, delete, and move files using Java's modern NIO.2 library.
Imagine managing boxes inside a warehouse:
- The Address (
Path): A piece of paper that reads: "Row 3, Shelf B, Box 5". It doesn't contain a box, it is just a written locator description. - The Crane Operator (
Files): This is the machine that takes the address, goes to the shelf, and actually creates, relocates, or deletes the box.
1. Defining a File Path
In NIO.2, we define locators using the Paths.get() helper, which returns a Path instance:
import java.nio.file.Path;
import java.nio.file.Paths;
Path path = Paths.get("C:/Users/soushaw/Desktop/testfile.txt");
2. Creating, Deleting, and Moving Files
Once you have a Path reference, you pass it to static helper methods inside the Files utility class:
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class FileManip {
public static void main(String[] args) {
Path path = Paths.get("C:/Users/soushaw/Desktop/testfile.txt");
// 1. Creating a file
try {
Files.createFile(path);
System.out.println("File created!");
} catch (IOException e) {
System.out.println("Could not create file: " + e.getMessage());
}
// 2. Moving a file
try {
Path targetPath = Paths.get("C:/Users/soushaw/Desktop/archive/testfile.txt");
Files.move(path, targetPath);
System.out.println("File moved!");
} catch (IOException e) {
System.out.println("Could not move file: " + e.getMessage());
}
// 3. Deleting a file
try {
Path targetPath = Paths.get("C:/Users/soushaw/Desktop/archive/testfile.txt");
Files.deleteIfExists(targetPath);
System.out.println("File deleted!");
} catch (IOException e) {
System.out.println("Could not delete file: " + e.getMessage());
}
}
}
Conclusion
Java NIO.2 is the standard for file management in modern enterprise applications. Its method calls (like Files.deleteIfExists()) prevent resource leaks and throw clear exceptions, protecting your program from unexpected system lockouts.