java · level 2 · unit 7 · lesson 2
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
A keeps your text after the program ends.
Everything in your boxes vanishes when a program ends. A file keeps it. names the path to a file in the current folder, and Files.writeString(path, text) saves text there, making the file or replacing what it held.
Files.readString(path) reads it all back as one string, and Files.exists(path) checks whether the file is there. All three live in java.nio.file, so import java.nio.file.*.
Files can fail in ways that are nobody's fault, so these methods throw , a checked exception. The simplest way to deal with it is to declare it: main(String[] args) throws IOException.
import java.io.IOException;
import java.nio.file.*;
public class Main {
public static void main(String[] args) throws IOException {
Path path = Path.of("diary.txt");
System.out.println("Exists before: " + Files.exists(path));
Files.writeString(path, "Dear diary, I learned about files today.");
System.out.println("Exists after: " + Files.exists(path));
System.out.println(Files.readString(path));
}
} Write a file before you read it, or Java stops with a NoSuchFileException.
guess first
Save twice, read once. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
import java.io.IOException;
import java.nio.file.*;
public class Main {
public static void main(String[] args) throws IOException {
Path path = Path.of("score.txt");
Files.writeString(path, "10");
Files.writeString(path, "25");
String saved = Files.readString(path);
System.out.println("Saved score: " + saved);
System.out.println(Integer.parseInt(saved) + 5);
}
}
your turn
Your turn. Leave yourself a note.
Type a note of your own between the quotes on line 6. Then press run to save it and read it back.
output
press run to see what happens
fix it
The shopping list went missing. Fix it!
output
press run to see what happens
- Java stopped with a
NoSuchFileExceptionon line 6. Which file is it trying to read? - The file saved on line 5 and the one read on line 6 have different names. One letter is missing.
- Change
shoping.txttoshopping.txton line 6, then press run.
nailed it
your program remembers after it ends. :D
Files.writeStringsaves text in a file.Files.readStringreads it all back.- File methods throw
IOException, so declare it withthrows.
new words in your collection
- file
- path
- IOException
This lesson isn’t saved. A free account remembers every lesson you finish.