Summary - File I/O
- Java course
- Intermediate
- Lesson 75/116
- 5 min
Combine BufferedReader and PrintWriter to write a notes app.
Summary - File operations
In this group you learned file operations. File represents a path; FileWriter and FileReader read and write characters. With BufferedReader you read line by line, with PrintWriter you write formatted output. try-with-resources closed resources automatically.
This summary combines everything in a small task: write lines to a file and then read them back.
Practice Write and read back
First, in a try (PrintWriter pw = new PrintWriter("summary.txt", "UTF-8")) block, write pw.println("One"); and pw.println("Two");. Then, in a try (BufferedReader r = new BufferedReader(new FileReader("summary.txt"))) block, call System.out.println(r.readLine()); twice.
Starter code
import java.io.PrintWriter;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class Main {
public static void main(String[] args) throws IOException {
// Open PrintWriter with try-with-resources, write two lines
// Open BufferedReader with try-with-resources, read two lines and print
}
}Sample solution
import java.io.PrintWriter;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class Main {
public static void main(String[] args) throws IOException {
try (PrintWriter pw = new PrintWriter("summary.txt", "UTF-8")) {
pw.println("One");
pw.println("Two");
}
try (BufferedReader r = new BufferedReader(new FileReader("summary.txt"))) {
System.out.println(r.readLine());
System.out.println(r.readLine());
}
}
}Expected output
One Two
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which structure auto-closes resources?
- try-with-resources Correct answer
- try { } catch
- finally { }
- static import
Explanation: try-with-resources calls close automatically at the end.
2 Complete the line-reading method
String line = r.____();
String line = r.readLine();
Explanation: readLine returns one line.
3 Match the file operations summary
| Term | Meaning |
|---|---|
File |
Represents a path |
BufferedReader |
Reads line by line |
PrintWriter |
Writes formatted output |
try-with-resources |
Auto-closes resources |