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