Search⌘ K
AI Features

Solution: Game State Saver

Explore how to implement game state saving in Java by making Player objects serializable, using ObjectOutputStream and ObjectInputStream with NIO.2 file streams. Learn how to handle exceptions and ensure safe resource management with try-with-resources to persist and restore objects efficiently.

We'll cover the following...
Java 25
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
public class GameSaver {
// Mark the class as Serializable
public static class Player implements Serializable {
private String name;
private int level;
private double health;
public Player(String name, int level, double health) {
this.name = name;
this.level = level;
this.health = health;
}
@Override
public String toString() {
return "Player[name=" + name + ", level=" + level + ", health=" + health + "]";
}
}
public static void saveGame(Player player, String fileName) {
Path path = Path.of(fileName);
// Use try-with-resources for automatic cleanup
try (ObjectOutputStream out = new ObjectOutputStream(Files.newOutputStream(path))) {
out.writeObject(player);
} catch (IOException e) {
e.printStackTrace();
}
}
public static Player loadGame(String fileName) {
Path path = Path.of(fileName);
// Use try-with-resources to read the object back
try (ObjectInputStream in = new ObjectInputStream(Files.newInputStream(path))) {
return (Player) in.readObject();
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
return null;
}
}
public static void main(String[] args) {
String saveFile = "savegame.dat";
Player originalPlayer = new Player("Hero", 5, 100.0);
System.out.println("Saving: " + originalPlayer);
saveGame(originalPlayer, saveFile);
System.out.println("Loading...");
Player loadedPlayer = loadGame(saveFile);
if (loadedPlayer != null) {
System.out.println("Loaded: " + loadedPlayer);
System.out.println("Success: " + originalPlayer.toString().equals(loadedPlayer.toString()));
} else {
System.out.println("Failed to load game.");
}
}
}
...