【问题标题】:How can I delete serialized objects in Java? [closed]如何删除 Java 中的序列化对象? [关闭]
【发布时间】:2021-03-26 08:05:48
【问题描述】:

为什么当我实现 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.");
        }

【问题讨论】:

  • close() 释放文件句柄。文档是你的朋友docs.oracle.com/javase/7/docs/api/java/io/…
  • 您可以通过删除存储字节的任何内容来删除序列化对象——文件、字节数组等等。
  • 似乎您已经知道答案:您必须关闭输出流。使用 try-with-resources 可以做得更好。

标签: java file oop serialization stream


【解决方案1】:

每当您创建资源时,您必须关闭它。不这样做意味着会发生各种不好的事情:无法删除文件只是其中之一;另一个应用程序最终会因为 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.

【讨论】:

  • 如果ObjectOutputStream也在其中,则不需要将FileOutputStream放在try-with-resources中的单独语句中;关闭 ObjectOutputStream 将关闭其底层流。
  • .. 当然,除非 OOS 在施工期间死亡。诚然,这种情况很少见,但将整个链放在 try 块中是更好的方式。您可以使用var 减少一些噪音。这种语法存在是有原因的。
猜你喜欢
  • 2013-07-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-02-08
  • 2023-03-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多