Complete Example: Reading and Writing Text Files
You'll learn how to combine BufferedReader, BufferedWriter, and try-with-resources into a complete, production-ready text file processing program.
Now that you've learned the individual pieces—BufferedReader, BufferedWriter, line-by-line reading, and automatic resource management—it's time to see them work together in a real-world scenario.
The Complete Pattern
Here's a full program that safely reads a text file line by line, processes each line, and writes the result to a new file:
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class TextFileProcessor {
public static void main(String[] args) {
String inputFile = "input.txt";
String outputFile = "output.txt";
// Try-with-resources ensures both streams close automatically
try (BufferedReader reader = new BufferedReader(new FileReader(inputFile));
BufferedWriter writer = new BufferedWriter(new FileWriter(outputFile))) {
String line;
while ((line = reader.readLine()) != null) {
// Process each line (example: convert to uppercase)
String processed = line.toUpperCase();
writer.write(processed);
writer.newLine(); // Platform-independent line break
}
// flush() called automatically on close
System.out.println("File processing complete!");
} catch (IOException e) {
System.err.println("Error processing file: " + e.getMessage());
}
}
}
What This Demonstrates
- Both resources declared in one try-with-resources statement
- Buffering for efficient I/O on both sides
- Line-by-line processing with
readLine() - Platform-independent line endings with
newLine() - Automatic cleanup—both files close even if exceptions occur
Key Takeaway: Wrap FileReader in BufferedReader and FileWriter in BufferedWriter, declare both in try-with-resources, and use readLine() with newLine() for safe, efficient text file processing.