如何解决Java FileOutputStream try 块未运行它立即跳到 catch 块
这是我的字段:
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 块。我检查了所有字段,它们都是可序列化的,所以这不是问题。我哪里做错了?我使用了一个教程来获取代码。
解决方法
就像 David Zimmerman 所说,将 e.printStackTrace() 放在 catch 块中以查看异常。此外,我怀疑您执行的方法错误。对于您的实现,您必须执行以下操作:
Player p = new Player(...);
p.save(p);
我使用该代码进行了测试,并且运行良好。但这很丑陋,因为您必须将外部引用传递给对象本身。我建议您从“保存”功能中删除“播放器播放器”参数并以这种方式编写对象:
objectOut.writeObject(this);
然后你可以做这样的事情:
Player p = new Player();
p.save();
我以这种方式进行了测试,效果也很好。
如果您将资源自动关闭放在 try-with-resources 中(如 Raedwald 所说),您可以做得更好,这样您就不必担心关闭每个资源。
try (FileOutputStream out = new FileOutputStream(filename);
ObjectOutputStream objectOut = new ObjectOutputStream(out);) {
您可以删除以下行:
objectOut.close();
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。