Java NIO File Operations
Comprehensive guide to Java NIO file I/O operations using java.nio.file.Path and java.nio.file.Files APIs.
Core Concepts
Path Creation and Resolution
Path creation methods:
Paths.get("path/to/file")— Java 7+Path.of("path/to/file")— Java 11+ (shorthand for Paths.get())
Common Path operations:
Path p1 = Paths.get("some/folder/file.txt");
Path resolved = p1.resolve("child.txt"); // Append to path
Path parent = p1.getParent(); // Get parent directory
Path fileName = p1.getFileName(); // Get filename only
Path abs = p1.toAbsolutePath(); // Convert to absolute path
Path normalized = p1.normalize(); // Clean up "." and ".." segmentsFile Existence and Type Checking
Files.exists(path) // File exists
Files.notExists(path) // File does not exist
Files.isDirectory(path) // Is directory
Files.isRegularFile(path) // Is regular fileFile Creation
Directory Creation
Files.createDirectory(path) // Single level, throws if parent missing
Files.createDirectories(path) // Creates parent dirs as needed, safest optionFile Creation
Files.createFile(path) // Creates empty file, throws FileAlreadyExistsException if existsBest practice: Check existence first or handle exception appropriately.
File Reading
Java 11+ (Simplest)
String content = Files.readString(path); // Read entire file as StringJava 8+ (Compatible)
String content = new String(Files.readAllBytes(path), StandardCharsets.UTF_8);
List<String> lines = Files.readAllLines(path); // Read as List<String>Large Files (Stream-based)
try (Stream<String> lines = Files.lines(path)) {
lines.forEach(System.out::println);
}File Writing
Java 11+
Files.writeString(path, "content"); // Overwrite existing file
// Append mode
Files.writeString(path, "content",
StandardOpenOption.CREATE, StandardOpenOption.APPEND);Java 8+
Files.write(path, content.getBytes(StandardCharsets.UTF_8));
Files.write(path, linesList, StandardOpenOption.CREATE);File Operations
Copy/Move/Delete
Files.copy(src, dest, StandardCopyOption.REPLACE_EXISTING);
Files.move(src, dest, StandardCopyOption.REPLACE_EXISTING);
Files.delete(path); // Throws if file doesn't exist
Files.deleteIfExists(path); // Returns false if doesn't exist, saferDirectory Traversal
List Directories (One Level)
try (Stream<Path> stream = Files.list(dir)) {
stream.forEach(System.out::println);
}Recursive Walk
try (Stream<Path> stream = Files.walk(dir)) {
stream.filter(Files::isRegularFile)
.forEach(System.out::println);
}Search with Pattern
try (Stream<Path> stream = Files.find(dir, Integer.MAX_VALUE,
(p, attr) -> p.toString().endsWith(".txt"))) {
stream.forEach(System.out::println);
}File Information
long size = Files.size(path); // File size in bytes
FileTime modified = Files.getLastModifiedTime(path); // Last modified timestampJava Version Differences
Key Java 11+ Additions
Path.of()— Shorthand forPaths.get()Files.readString()— Direct string readingFiles.writeString()— Direct string writing
Java 8 Compatibility
- Use
Paths.get()instead ofPath.of() - Use
Files.readAllBytes()+new String()for text reading - Use
Files.write()with byte arrays for text writing
Best Practices
-
Resource Management: Always use try-with-resources for streams
try (Stream<String> lines = Files.lines(path)) { // Process lines } -
Exception Handling: Choose between exception-throwing vs safe methods
Files.createFile()throws if exists → CheckFiles.exists()firstFiles.delete()throws if missing → UseFiles.deleteIfExists()
-
Encoding: Always specify character encoding for text files
Files.readString(path, StandardCharsets.UTF_8) -
Options: Use
StandardOpenOptionfor write behavior controlCREATE— Create if doesn’t existAPPEND— Append to existing fileTRUNCATE_EXISTING— Overwrite existing content
References
- java-io — Java I/O operations overview
- java-streams — Java Stream API usage