AI Hints
Home›Java Tutorial›Writing Files, Reading Files, Practice: Save and Load
Java · Lesson 99 of 120

Practice: Save and Load

Put module eleven together.

⏱ 2 min read▶ Video at 2:05:20🎓 Free
Watch this lesson in the Java courseWatch on YouTube ↗Full Java course

Let's put module eleven together. Save a map of scores to a file, then load it back, and check nothing was lost.

  • Save a map
  • Load it back
  • Nothing lost

Save and load scores

Your turn. Pause the video, and try this. Save three players' scores to a file, one per line, as name equals score. Then read the file back into a new map, and check it matches the original. Here is one solution. Each entry becomes a line, like ana equals twelve. Files dot write saves the list. To load, we split each line at the equals sign, and parse the number. Run it. The loaded map is the same as the original.

✍️ Exercise: Save and load scores

Save scores as "name=score" lines, read them back into a new map, and check it equals the original.

Show hint

line.split("=") then Integer.parseInt

Show solution
Main.javajava
import java.io.IOException;
import java.nio.file.*;
import java.util.*;
public class Main {
    public static void main(String[] args) throws IOException {
        Map<String, Integer> scores = new TreeMap<>(Map.of("ana", 12, "ben", 9, "cy", 15));
        List<String> out = new ArrayList<>();
        for (String name : scores.keySet()) out.add(name + "=" + scores.get(name));
        Files.write(Path.of("scores.txt"), out);
        System.out.println("Saved " + out.size() + " scores");
        Map<String, Integer> loaded = new TreeMap<>();
        for (String line : Files.readAllLines(Path.of("scores.txt"))) {
            String[] kv = line.split("=");
            loaded.put(kv[0], Integer.parseInt(kv[1]));
        }
        System.out.println("Loaded: " + loaded);
        System.out.println("Same? " + scores.equals(loaded));
    }
}
Output
Saved 3 scores
Loaded: {ana=12, ben=9, cy=15}
Same? true

What module eleven taught

Exceptions signal problems. Try and catch handle them, and finally always runs. Checked exceptions must be caught or declared. Throw signals your own problems. And the Files class reads and writes files, with try with resources closing things for you.

keyvalue
Handletry, catch, finally
Signalthrow, custom exceptions
Ruleschecked vs unchecked
FileswriteString, readAllLines

Summary

Your programs can now handle errors, and keep data in files. That's the end of module eleven. Next module, modern Java.

Key takeaways
  • Exceptions
  • try-with-resources
  • Files
Next up: Lambdas — functions as values