Close a file created with FileOutputStream, for a next delete

user1619114 picture user1619114 · Aug 23, 2012 · Viewed 38.5k times · Source

I am currently facing some problem with a FileOutputStream in my Java code.

Actually I am using a FileOutputStream for creating a file, but then once the file is created there is no way for deleting it. As far as I could understand, this may come from the fact that the FileOutputstream is not closed.

On below my summarized code :

     outFile = new FileOutputStream(dir+"\\"+fileName);
     outFile.write("Test");
     outFile.flush();
     outFile.close();
     outFile = null;
     System.gc();

Then there is no way to delete the file, even "by hand". When my program is launched, I can't delete it on windows by a simple del. I also tried to remove content of the folder dir and it didn't worked neither, using this code :

static public void delDir( String place )

{
    File path = new File( place );
    System.out.println(path.exists());//return true
    if( path.exists() )
        {
        File[] f = path.listFiles();
        for( int j = 0 ; j < f.length ; j++ )
            {
            if( f[ j ].isDirectory() )
                {
                deleteDirectory( path+"\\"+f[ j ] );
                }
            f[ j ].delete();
            }
        }
}

So my question is : How to close this file for a next delete (or how to delete it properly if we can't close it)?

Answer

christian.vogel picture christian.vogel · Aug 23, 2012

It is a bug in Java. Yes it it rarely but they exists ;) Could you add after outFile.close()

outFile = null;
System.gc();

And then try to delete it. There are more possiblity if this is not working. Let me know.

UPDATE

For me it works:

public class FileDeleteExample {
    public static void main(String[] args) throws Exception {
        File f = new File("test.txt");

        FileOutputStream outFile = null;

        try {
            outFile = new FileOutputStream(f);
            outFile.write("Test".getBytes());
        } finally {
            outFile.flush();
            outFile.close();
            outFile = null;
            System.gc();
        }

        f.delete();
    }
}

UPDATE

I tried it with the example Sumit Singh mentioned by deleting the lines outFile=null; System.gc; and this works as well for me. So there should'nt be a problem with the FileOutputStream. Could you try the little example above and say whether it works or not?

UPDATE

void closeQuietly(FileOutputStream out) {
    try { out.flush(); out.close(); } catch(Exception e) {} 
}

Now just call the method in the finally block!