Working with File I/O (NIO.2)
1. Working with Path Interface
| Method | Use |
|---|---|
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 / getRoot | Components |
2. Working with Files Class
| Method | Use |
|---|---|
exists / notExists | Existence check |
isReadable / isWritable / isExecutable | Permissions |
isDirectory / isRegularFile | Type 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);
}
| Method | Best For |
|---|---|
readString(p) | Small text files |
readAllLines(p) | Small line-based files |
lines(p) | Large files (lazy) |
newBufferedReader(p) | Manual reading |
4. Writing Files
| Method | Use |
|---|---|
Files.writeString(p, s) | Write text |
Files.write(p, bytes) | Write bytes |
Files.write(p, lines) | Write line list |
| Options | CREATE, APPEND, TRUNCATE_EXISTING, WRITE |
5. Copying Files
| Method | Use |
|---|---|
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
| Method | Use |
|---|---|
Files.move(src, dst) | Move/rename |
| Options | REPLACE_EXISTING, ATOMIC_MOVE |
7. Deleting Files
| Method | Detail |
|---|---|
Files.delete(p) | Throws if missing |
Files.deleteIfExists(p) | Returns boolean |
8. Checking File Existence
| Method | Detail |
|---|---|
Files.exists(p, options) | true/false |
Files.notExists(p) | Distinguishes "not exists" vs "unknown" |
9. Creating Directories
| Method | Detail |
|---|---|
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);
}
| Method | Detail |
|---|---|
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
| Method | Use |
|---|---|
Files.newBufferedReader(p) | UTF-8 by default |
Files.newBufferedWriter(p, options) | Write |
reader.lines() | Stream of lines |
12. Working with File Attributes
| Method | Detail |
|---|---|
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
| Resource | Auto-close |
|---|---|
Stream<Path> from Files | Required (releases file handles) |
| Reader/Writer | Required |
| InputStream/OutputStream | Required |
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 Kind | Trigger |
|---|---|
ENTRY_CREATE | New file/dir |
ENTRY_DELETE | Removed |
ENTRY_MODIFY | Modified |
OVERFLOW | Events lost |