Working with NIO.2 File API
1. Using Path API
| Method | Use |
|---|---|
Path.of("a", "b") | Construct |
resolve(rel) / resolveSibling | Compose |
relativize(other) | Compute relative |
normalize() | Resolve .. / . |
toAbsolutePath / toRealPath | Absolute / canonical |
getFileName / getParent / getRoot | Components |
2. Working with Files API
| Method | Use |
|---|---|
exists / notExists / isDirectory | Probes |
createFile / createDirectory / createDirectories | Create |
copy / move / delete / deleteIfExists | Mutations |
size / probeContentType | Metadata |
| StandardCopyOption | REPLACE_EXISTING, ATOMIC_MOVE |
3. Reading Files
| Method | Returns |
|---|---|
readString(path) | String (small files) |
readAllBytes(path) | byte[] |
readAllLines(path) | List<String> |
lines(path) | Stream<String> (auto-close) |
newBufferedReader(path) | BufferedReader |
newInputStream(path) | InputStream |
4. Writing Files
| Method | Behavior |
|---|---|
writeString(path, str, options) | Java 11+ |
write(path, bytes / lines, options) | Bulk write |
newBufferedWriter / newOutputStream | Streaming |
| StandardOpenOption | CREATE, APPEND, TRUNCATE_EXISTING, SYNC |
5. Walking File Trees
| API | Use |
|---|---|
Files.walk(path[, maxDepth]) | Stream<Path> — recursive |
Files.walkFileTree(path, visitor) | Visitor pattern |
Files.find(path, depth, matcher) | Filtered walk |
Files.list(path) | Direct children |
6. Watching Directories (WatchService)
Example: Watch directory
WatchService ws = FileSystems.getDefault().newWatchService();
dir.register(ws, StandardWatchEventKinds.ENTRY_CREATE,
StandardWatchEventKinds.ENTRY_MODIFY);
WatchKey key;
while ((key = ws.take()) != null) {
for (WatchEvent<?> e : key.pollEvents()) handle(e);
key.reset();
}
| Event | Meaning |
|---|---|
| ENTRY_CREATE | New file/dir |
| ENTRY_MODIFY | Content/metadata change |
| ENTRY_DELETE | Removed |
| OVERFLOW | Events lost |
7. Using File Attributes
| API | Returns |
|---|---|
readAttributes(path, BasicFileAttributes.class) | size, times, type |
PosixFileAttributes | permissions, owner |
DosFileAttributes | readonly, hidden |
| UserDefined | Extended attributes |
8. Working with Symbolic Links
| API | Use |
|---|---|
createSymbolicLink(link, target) | Create |
readSymbolicLink(link) | Resolve target |
isSymbolicLink(path) | Test |
| LinkOption.NOFOLLOW_LINKS | Don't dereference |
9. Using Temporary Files and Directories
| API | Use |
|---|---|
createTempFile(prefix, suffix) | System temp |
createTempDirectory(prefix) | System temp dir |
| DELETE_ON_CLOSE | Auto-cleanup |
| Java 1.7+ | NIO replaces File.createTempFile |
10. Understanding Memory-Mapped Files
| API | Use |
|---|---|
FileChannel.map(mode, pos, size) | Returns MappedByteBuffer |
| MapMode | READ_ONLY / READ_WRITE / PRIVATE |
force() | Flush to disk |
| Use | Large files, random access |
| Modern | Foreign Memory API for off-heap |
11. Using FileSystem API
| API | Use |
|---|---|
FileSystems.getDefault() | Native FS |
FileSystems.newFileSystem(URI, env) | ZIP/JAR as FS |
fs.getPath("/x/y") | FS-specific path |
Example: Read from ZIP
try (FileSystem zip = FileSystems.newFileSystem(URI.create("jar:" + path.toUri()), Map.of())) {
Files.copy(zip.getPath("/inside.txt"), Path.of("out.txt"));
}
12. Using AsynchronousFileChannel
| API | Returns |
|---|---|
open(path, options) | Channel |
read / write(buf, pos) | Future<Integer> or with handler |
| CompletionHandler | Callback API |
| Use | True async I/O without dedicated thread |