java · level 2 · unit 7 · lesson 4
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
closes your files for you, even after an error.
For bigger files, write bit by bit with a . It collects text and writes it in batches, so you must it at the end, or the last batch may never reach the file. People forget, and an exception can skip the line that closes it.
Try-with-resources solves both. Open the writer inside the try brackets: try (BufferedWriter out = Files.newBufferedWriter(path)) { }. When the block ends, Java closes it for you, even after an exception.
.write adds text and .newLine() ends the line. To read back, open new Scanner(path) the same way, and loop while is true.
import java.io.*;
import java.nio.file.*;
import java.util.Scanner;
public class Main {
public static void main(String[] args) throws IOException {
Path path = Path.of("todo.txt");
String[] jobs = {"Feed the cat", "Water the plants", "Do homework"};
try (BufferedWriter out = Files.newBufferedWriter(path)) {
for (String job : jobs) {
out.write(job);
out.newLine();
}
}
try (Scanner in = new Scanner(path)) {
while (in.hasNextLine()) {
System.out.println("To do: " + in.nextLine());
}
}
}
} A try with brackets needs no catch, but you can add one.
guess first
Write two scores, then add them up. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
import java.io.*;
import java.nio.file.*;
import java.util.Scanner;
public class Main {
public static void main(String[] args) throws IOException {
Path path = Path.of("scores.txt");
try (BufferedWriter out = Files.newBufferedWriter(path)) {
out.write("12");
out.newLine();
out.write("30");
}
int total = 0;
try (Scanner in = new Scanner(path)) {
while (in.hasNextLine()) {
total = total + Integer.parseInt(in.nextLine());
}
}
System.out.println("Total: " + total);
}
}
your turn
Your turn. Write a packing list.
Add an item of your own on line 7. On line 11, fill in the writer method that ends a line. Then press run.
output
press run to see what happens
fix it
The poem never reached the file. Fix it!
output
press run to see what happens
- It says 0 lines saved. The writer collected the poem, but did its batch ever reach the file?
- The writer is never closed, so its batch is never written. Let try-with-resources close it.
- Put line 6's writer in
try ( )brackets, wrap lines 7 to 9 in its block, then press run.
nailed it
you saved your work like a pro. :D
- Open files in
try ( )brackets, and Java closes them. .writeadds text, and.newLine()ends the line.- Read back with a
ScannerwhilehasNextLine()istrue.
new words in your collection
- BufferedWriter
- close
- try-with-resources
- hasNextLine
This lesson isn’t saved. A free account remembers every lesson you finish.