Lesson 43: Basic File Handling: Reading and Writing Files
Java handles file operations using Input/Output (I/O) classes. We will focus on the modern approach introduced in Java 7: NIO.2 (java.nio.file).
1. The Path Interface
In NIO.2, the Path interface represents a file system path, making path manipulation cross-platform and easier.
java import java.nio.file.Path; import java.nio.file.Paths;
// Create a Path object Path filePath = Paths.get("data", "info.txt"); System.out.println(filePath.toAbsolutePath());
2. Reading a File (Simplified)
The Files utility class provides simple static methods for common operations.
java import java.nio.file.Files; import java.nio.charset.StandardCharsets; import java.io.IOException; import java.util.List;
Path path = Paths.get("example.txt");
try {
// Reads all lines into a List
3. Writing to a File (Simplified)
java import static java.nio.file.StandardOpenOption.CREATE; import static java.nio.file.StandardOpenOption.APPEND;
Path outputPath = Paths.get("output.log"); String content = "Log entry: " + LocalDateTime.now();
try { // Writes content, creating the file if necessary, and appending to it. Files.write(outputPath, content.getBytes(), CREATE, APPEND); } catch (IOException e) { e.printStackTrace(); }
Note: Traditional file operations use FileInputStream/FileOutputStream (byte streams) or FileReader/FileWriter (character streams). The NIO.2 Files class provides cleaner, high-level methods that often handle the stream management for you.