Working with File I/O (NIO.2)

1. Working with Path Interface

MethodUse
Path.of("dir", "file.txt")Java 11+ factory
Paths.get(...)Older API
resolve(other)Append path
relativize(other)Relative path between
normalize()Remove redundancies
toAbsolutePath() / toRealPath()Resolve
getFileName / getParent / getRootComponents

2. Working with Files Class

MethodUse
exists / notExistsExistence check
isReadable / isWritable / isExecutablePermissions
isDirectory / isRegularFileType check
size(p)File size

3. Reading Files

Example: Read patterns

String content = Files.readString(path);                   // small files
List<String> lines = Files.readAllLines(path);
byte[] bytes = Files.readAllBytes(path);

try (Stream<String> stream = Files.lines(path)) {
    stream.filter(l -> !l.isBlank()).forEach(System.out::println);
}
MethodBest For
readString(p)Small text files
readAllLines(p)Small line-based files
lines(p)Large files (lazy)
newBufferedReader(p)Manual reading

4. Writing Files

MethodUse
Files.writeString(p, s)Write text
Files.write(p, bytes)Write bytes
Files.write(p, lines)Write line list
OptionsCREATE, APPEND, TRUNCATE_EXISTING, WRITE

5. Copying Files

MethodUse
Files.copy(src, dst)File-to-file
Files.copy(src, dst, REPLACE_EXISTING, COPY_ATTRIBUTES)With options
Files.copy(input, dst)From InputStream

6. Moving Files

MethodUse
Files.move(src, dst)Move/rename
OptionsREPLACE_EXISTING, ATOMIC_MOVE

7. Deleting Files

MethodDetail
Files.delete(p)Throws if missing
Files.deleteIfExists(p)Returns boolean

8. Checking File Existence

MethodDetail
Files.exists(p, options)true/false
Files.notExists(p)Distinguishes "not exists" vs "unknown"

9. Creating Directories

MethodDetail
Files.createDirectory(p)Single dir; throws if parent missing
Files.createDirectories(p)All intermediate dirs
Files.createTempDirectory(prefix)Temp dir

10. Listing Directory Contents

Example: Walk file tree

try (Stream<Path> entries = Files.list(dir)) {
    entries.forEach(System.out::println);
}
try (Stream<Path> tree = Files.walk(root, 3)) {
    tree.filter(Files::isRegularFile)
        .filter(p -> p.toString().endsWith(".log"))
        .forEach(System.out::println);
}
MethodDetail
list(p)Direct children
walk(p, depth)Recursive traversal
find(p, depth, biPred)Filtered walk
walkFileTree(p, visitor)Visitor pattern

11. Using BufferedReader and BufferedWriter

MethodUse
Files.newBufferedReader(p)UTF-8 by default
Files.newBufferedWriter(p, options)Write
reader.lines()Stream of lines

12. Working with File Attributes

MethodDetail
Files.getLastModifiedTime(p)FileTime
Files.getOwner(p)UserPrincipal
Files.readAttributes(p, BasicFileAttributes.class)Bulk
Files.setPosixFilePermissions(p, perms)POSIX permissions

13. Using try-with-resources for I/O

ResourceAuto-close
Stream<Path> from FilesRequired (releases file handles)
Reader/WriterRequired
InputStream/OutputStreamRequired

14. Watching Directories

Example: WatchService

try (WatchService ws = FileSystems.getDefault().newWatchService()) {
    dir.register(ws, ENTRY_CREATE, ENTRY_MODIFY, ENTRY_DELETE);
    while (true) {
        WatchKey key = ws.take();
        for (WatchEvent<?> e : key.pollEvents()) {
            System.out.println(e.kind() + ": " + e.context());
        }
        if (!key.reset()) break;
    }
}
Event KindTrigger
ENTRY_CREATENew file/dir
ENTRY_DELETERemoved
ENTRY_MODIFYModified
OVERFLOWEvents lost