Working with NIO.2 File API

1. Using Path API

MethodUse
Path.of("a", "b")Construct
resolve(rel) / resolveSiblingCompose
relativize(other)Compute relative
normalize()Resolve .. / .
toAbsolutePath / toRealPathAbsolute / canonical
getFileName / getParent / getRootComponents

2. Working with Files API

MethodUse
exists / notExists / isDirectoryProbes
createFile / createDirectory / createDirectoriesCreate
copy / move / delete / deleteIfExistsMutations
size / probeContentTypeMetadata
StandardCopyOptionREPLACE_EXISTING, ATOMIC_MOVE

3. Reading Files

MethodReturns
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

MethodBehavior
writeString(path, str, options)Java 11+
write(path, bytes / lines, options)Bulk write
newBufferedWriter / newOutputStreamStreaming
StandardOpenOptionCREATE, APPEND, TRUNCATE_EXISTING, SYNC

5. Walking File Trees

APIUse
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();
}
EventMeaning
ENTRY_CREATENew file/dir
ENTRY_MODIFYContent/metadata change
ENTRY_DELETERemoved
OVERFLOWEvents lost

7. Using File Attributes

APIReturns
readAttributes(path, BasicFileAttributes.class)size, times, type
PosixFileAttributespermissions, owner
DosFileAttributesreadonly, hidden
UserDefinedExtended attributes
APIUse
createSymbolicLink(link, target)Create
readSymbolicLink(link)Resolve target
isSymbolicLink(path)Test
LinkOption.NOFOLLOW_LINKSDon't dereference

9. Using Temporary Files and Directories

APIUse
createTempFile(prefix, suffix)System temp
createTempDirectory(prefix)System temp dir
DELETE_ON_CLOSEAuto-cleanup
Java 1.7+NIO replaces File.createTempFile

10. Understanding Memory-Mapped Files

APIUse
FileChannel.map(mode, pos, size)Returns MappedByteBuffer
MapModeREAD_ONLY / READ_WRITE / PRIVATE
force()Flush to disk
UseLarge files, random access
ModernForeign Memory API for off-heap

11. Using FileSystem API

APIUse
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

APIReturns
open(path, options)Channel
read / write(buf, pos)Future<Integer> or with handler
CompletionHandlerCallback API
UseTrue async I/O without dedicated thread