File Operations Guide
File Creation and Management
Creating Files
Path newFile = Files.createFile(Paths.get("/home/labex/example.txt"));
Creating Directories
Path newDirectory = Files.createDirectories(Paths.get("/home/labex/newdir"));
File Writing Techniques
Writing Text Files
// Write entire content
Files.write(
Paths.get("/home/labex/document.txt"),
"Hello, LabEx Developer!".getBytes()
);
// Write with specific options
Files.write(
Paths.get("/home/labex/log.txt"),
lines,
StandardCharsets.UTF_8,
StandardOpenOption.APPEND
);
Writing Large Files
try (BufferedWriter writer = Files.newBufferedWriter(
Paths.get("/home/labex/largefile.txt"),
StandardCharsets.UTF_8
)) {
writer.write("Streaming content efficiently");
}
File Reading Strategies
Reading Entire File
List<String> lines = Files.readAllLines(
Paths.get("/home/labex/data.txt")
);
Reading Large Files
try (Stream<String> lineStream = Files.lines(
Paths.get("/home/labex/bigdata.txt")
)) {
lineStream.forEach(System.out::println);
}
File Manipulation Operations
graph TD
A[File Operations] --> B[Copy]
A --> C[Move]
A --> D[Delete]
A --> E[Attributes]
Copying Files
Files.copy(
Paths.get("/home/labex/source.txt"),
Paths.get("/home/labex/destination.txt"),
StandardCopyOption.REPLACE_EXISTING
);
Moving Files
Files.move(
Paths.get("/home/labex/oldlocation.txt"),
Paths.get("/home/labex/newlocation.txt"),
StandardCopyOption.REPLACE_EXISTING
);
Deleting Files
Files.delete(Paths.get("/home/labex/temporary.txt"));
File Attributes Management
Reading File Attributes
Path filePath = Paths.get("/home/labex/example.txt");
BasicFileAttributes attrs = Files.readAttributes(
filePath,
BasicFileAttributes.class
);
Attribute Types
| Attribute |
Description |
Access Method |
| Size |
File size |
attrs.size() |
| Creation Time |
File creation timestamp |
attrs.creationTime() |
| Last Modified |
Last modification time |
attrs.lastModifiedTime() |
Advanced File Operations
Recursive Directory Deletion
Files.walk(Paths.get("/home/labex/temp"))
.sorted(Comparator.reverseOrder())
.map(Path::toFile)
.forEach(File::delete);
File Searching
try (Stream<Path> pathStream = Files.find(
Paths.get("/home/labex"),
Integer.MAX_VALUE,
(path, attrs) -> attrs.isRegularFile()
)) {
pathStream.forEach(System.out::println);
}
Error Handling Best Practices
try {
Files.createFile(Paths.get("/home/labex/newfile.txt"));
} catch (IOException e) {
// Proper error management
System.err.println("File creation failed: " + e.getMessage());
}
Conclusion
Mastering file operations in Java requires understanding various methods, handling exceptions, and choosing appropriate techniques for different scenarios.