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)); }}
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.