3 Replies Latest reply: Mar 27, 2007 1:50 AM by 807596 RSS

    file delete fails before garbage collect?

    807596
      Hi,
      I've got a program that does some processing which creates a load of files in a directory and then deletes them later. Occasionally one of the files does not get deleted (file.delete returns false).
      From reading around I've heard that this can happen on Windows when
      1) You create a file
      2) You close the underlying stream
      3) You try and delete the file, but it fails.
      The theory is that because the File object hasn't yet been garbage collected the underlying file descriptor has not been released to the operating system. Windows still counts the file as Open, and so the delete fails. I've seen putting System.gc() before file.delete() as a workaround - though obviosuly this isn't guaranteed to work.,
      Is this true? If so, does someone have a bug ID? Is there a better workaround?

      Thanks and regards,

      Simon
        • 1. Re: file delete fails before garbage collect?
          807596
          I have JDK 1.4.2_04 on Windows 2000.
          public class A {
              public static void main(String[] args) throws FileNotFoundException, IOException {
                  File f = new File("deletem");
                  FileOutputStream fos = new FileOutputStream(f);
                  fos.write(1);
                  fos.close();
                  System.out.println("exists="+f.exists());
                  System.out.println("delete="+f.delete());
                  System.out.println("exists="+f.exists());
              }
          }
          Produces
          exists=true
          delete=true
          exists=false
          • 2. Re: file delete fails before garbage collect?
            807596
            Never happend to me but the OP said it happend occaionally only, what about this small change in the example above to make sure the FileOutputStream is ready to be deleted:
            public class A {
                public static void main(String[] args) throws FileNotFoundException, IOException {
                    File f = new File("deletem");
                    FileOutputStream fos = new FileOutputStream(f);
                    fos.write(1);
                    fos.close();
                 fos=null; //make sure it can be deleted by GarbageCollector
                    System.out.println("exists="+f.exists());
                    System.out.println("delete="+f.delete());
                    System.out.println("exists="+f.exists());
                }
            }
            • 3. Re: file delete fails before garbage collect?
              807596
              Try reading this link:

              http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6266377