Java FileOutputStream try 块未被 运行。它立即跳到 catch 块

Java FileOutputStream try block is not being run. It immediately skips to the catch block

这是我的字段:

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 块都会立即被跳过。捕获块是 运行。我检查了所有字段,它们都是可序列化的,所以这不是问题所在。我哪里做错了?我用教程把代码弄下来了。

就像 David Zimmerman 所说,将 e.printStackTrace() 放在 catch 块中以查看异常。另外我怀疑你执行的方法有误。对于您的实施,您必须执行以下操作:

Player p = new Player(...);
p.save(p);

我用那个代码做了一个测试,它工作正常。但这很丑陋,因为您必须将外部引用传递给对象本身。我建议您从“保存”函数中删除“Player player”参数并以这种方式编写对象:

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();