How can I delete serialized objects in Java? [closed]

Why when I implement the method oos.close() it works(I mean it deletes the file), else – not?

       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.");
        }

Answer

Whenever you create a resource, you must close it. Failure to do so means various bad things happen: The inability to delete files is just one of them; an app that will eventually just hardcrash because the VM ran out of file handles is another.

To do so, use the try-with-resources construct. So, don’t do what you wrote. Instead:

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.

Leave a Reply

Your email address will not be published. Required fields are marked *