File I/O & NIO
Duration: 7 min
Java provides two main approaches for file input/output: the traditional I/O (java.io) and the newer NIO (java.nio). Traditional I/O uses streams and readers/writers, while NIO uses channels and buffers for more efficient file operations. Understanding both is essential for working with files effectively.
FileReader, FileWriter, and BufferedReader
Visual Guide: This module includes diagrams and flowcharts. Check the course materials for detailed visualizations.
The traditional I/O approach uses character streams for text files. BufferedReader improves performance by buffering input.
import java.io.*;
public class TraditionalFileIO {
public static void main(String[] args) throws IOException {
// Writing to a file
FileWriter writer = new FileWriter("output.txt");
writer.write("Hello, World!\n");
writer.write("This is a test file.");
writer.close();
// Reading from a file
BufferedReader reader = new BufferedReader(new FileReader("output.txt"));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
reader.close();
}
}Hello, World!
This is a test file.Try-with-Resources
Try-with-resources automatically closes resources, preventing resource leaks. Any resource implementing AutoCloseable can be used.
import java.io.*;
public class TryWithResources {
public static void main(String[] args) {
// Writing with try-with-resources
try (FileWriter writer = new FileWriter("data.txt")) {
writer.write("Line 1\n");
writer.write("Line 2\n");
writer.write("Line 3");
} catch (IOException e) {
e.printStackTrace();
}
// Reading with try-with-resources
try (BufferedReader reader = new BufferedReader(new FileReader("data.txt"))) {
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}Line 1
Line 2
Line 3Java NIO: Path and Files
The NIO API provides Path and Files classes for modern file operations. Files offers convenient static methods for common operations.
import java.nio.file.*;
import java.util.List;
public class NIOFileOperations {
public static void main(String[] args) throws Exception {
// Create a path
Path path = Paths.get("nio_file.txt");
// Write all lines at once
List<String> lines = List.of("First line", "Second line", "Third line");
Files.write(path, lines);
// Read all lines at once
List<String> readLines = Files.readAllLines(path);
readLines.forEach(System.out::println);
// Check if file exists
System.out.println("File exists: " + Files.exists(path));
// Get file size
System.out.println("File size: " + Files.size(path) + " bytes");
}
}First line
Second line
Third line
File exists: true
File size: 42 bytesReading and Writing Files with NIO
NIO provides efficient byte-level operations using channels and buffers.
import java.nio.file.*;
import java.nio.charset.StandardCharsets;
public class NIOChannelIO {
public static void main(String[] args) throws Exception {
Path path = Paths.get("channel_file.txt");
// Write using Files.writeString
String content = "Hello from NIO!\nThis is efficient file I/O.";
Files.writeString(path, content, StandardCharsets.UTF_8);
// Read using Files.readString
String readContent = Files.readString(path);
System.out.println(readContent);
// Read as bytes
byte[] bytes = Files.readAllBytes(path);
System.out.println("\nFile size in bytes: " + bytes.length);
}
}Hello from NIO!
This is efficient file I/O.
File size in bytes: 45Working with Directories
Both traditional I/O and NIO support directory operations. NIO provides more convenient methods.
import java.nio.file.*;
import java.io.IOException;
public class DirectoryOperations {
public static void main(String[] args) throws IOException {
Path dir = Paths.get("my_directory");
// Create directory
if (!Files.exists(dir)) {
Files.createDirectory(dir);
System.out.println("Directory created");
}
// Create a file in the directory
Path file = dir.resolve("test.txt");
Files.writeString(file, "Content in subdirectory");
// List all files in directory
System.out.println("Files in directory:");
try (DirectoryStream<Path> stream = Files.newDirectoryStream(dir)) {
for (Path entry : stream) {
System.out.println(" " + entry.getFileName());
}
}
// Delete file
Files.delete(file);
System.out.println("File deleted");
}
}Directory created
Files in directory:
test.txt
File deletedCopying and Moving Files
NIO makes it easy to copy and move files with various options.
import java.nio.file.*;
public class FileCopyMove {
public static void main(String[] args) throws Exception {
Path source = Paths.get("source.txt");
Path copy = Paths.get("copy.txt");
Path destination = Paths.get("moved.txt");
// Create source file
Files.writeString(source, "Original content");
// Copy file
Files.copy(source, copy, StandardCopyOption.REPLACE_EXISTING);
System.out.println("File copied");
// Move file
Files.move(copy, destination, StandardCopyOption.REPLACE_EXISTING);
System.out.println("File moved");
// Verify
System.out.println("Source exists: " + Files.exists(source));
System.out.println("Destination exists: " + Files.exists(destination));
}
}File copied
File moved
Source exists: true
Destination exists: true❓ Which class is used to read text files line by line in traditional I/O?
❓ What is the main advantage of try-with-resources?
❓ Which NIO class represents a file or directory path?
❓ What does Files.readAllLines() return?
❓ Which method is used to list files in a directory using NIO?
Learn more: https://docs.oracle.com/javase/tutorial/i18n/resbundle/propfile.html