如何删除java中的序列化对象?

eqfvzcg8  于 2021-07-03  发布在  Java
关注(0)|答案(1)|浏览(481)

关闭。这个问题需要细节或清晰。它目前不接受答案。
**想改进这个问题吗?**通过编辑这个帖子来添加细节并澄清问题。

24天前关门。
改进这个问题
为什么当我实现oos.close()方法时它能工作(我的意思是它删除文件),否则-不行?

File newFile = new File("D:\\1.ser");
        try {
            ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(newFile));
            oos.writeObject(new A());
            oos.close();
        }catch (Exception e){
            e.printStackTrace();
        }
        if(newFile.delete()){
            System.out.println(newFile.getName() + " is deleted!");
        }else{
            System.out.println("Delete operation is failed.");
        }
wvt8vs2t

wvt8vs2t1#

无论何时创建资源,都必须将其关闭。不这样做意味着各种各样的坏事发生:无法删除文件只是其中之一;另一个应用程序最终会因为vm耗尽文件句柄而硬崩溃。
为此,请使用try with resources构造。所以,别照你写的做。取而代之的是:

File newFile = new File("D:\\1.ser");
try (FileOutputStream fos = new FileOutputStream(newFile);
     ObjectOutputStream oos = new ObjectOutputStream(fos)) {

    oos.writeObject(new A());
}
// oos and fos are neccessarily closed here...
// even if exceptions occurred. That's nice!
// thus.. delete will work here.

相关问题