【发布时间】:2021-08-04 17:09:17
【问题描述】:
这是我的字段:
final class Player implements Serializable{
/**
*
*/
private static final long serialVersionUID = 2676858593456923114L;
private final transient String filename = "BSR.data";
private int hp;
@SuppressWarnings("rawtypes")
private ArrayList<ArrayList> inventory = new ArrayList<>(); //This will be used to store the other
//inventories.
private ArrayList<String> myLevelUps = new ArrayList<>(); //This will be used to store the collection
//of level up items the player gets.
private ArrayList<Crystal> myCrystals = new ArrayList<>(); //This will be used to store the
//collection of crystals that the player
//gets.
private ArrayList<Weapon> myWeapons = new ArrayList<>(); //This will be used to store the collection
//of weapons that the player gets.
private int myLevel = 0;//a modifier.
private int myGold;
这是没有做它应该做的方法:
void save(Player player) {
try
{
// Create a file to write game system
FileOutputStream out = new FileOutputStream (filename);
// Code to write instance of Player will go here
ObjectOutputStream objectOut = new ObjectOutputStream (out);
// Write Player system to object store
objectOut.writeObject (player);
// Close object output stream
objectOut.close();
System.out.println("Your game has been saved to" + filename);
}
catch (Exception e)
{
System.err.println ("Unable to create game data");
}
}
应该发生的是使用字段中的文件名创建文件。但是,正如问题所述,整个 try 块被立即跳过。并运行 catch 块。我检查了所有字段,它们都是可序列化的,所以这不是问题。我哪里做错了?我使用教程来获取代码。
【问题讨论】:
-
我们需要查看异常。在你的 catch 块中,e.printStackTrace() 以便你可以看到发生了什么
-
把
catch中的代码改成e.printStackTrace(),看看哪里出错了。 -
如果方法
save在类Player中,也许你应该把它设为静态方法? -
您确实应该打印异常堆栈跟踪以了解更多信息。但是,如果您在尝试的第一行(初始化 FileOutputStream 的位置)遇到异常,则文件“BSR.data”很可能不在 Java 进程运行的位置。
-
你应该了解 try-with-resources。
标签: java fileoutputstream serializable