Apache commons-io FileUtils.deleteDirectory is not working properly

Boris Šuška picture Boris Šuška · Jul 24, 2013 · Viewed 8.6k times · Source

I've a problem with commons-io FileUtils.deleteDirectory(File). I simply call

FileUtils.deleteDirectory(new File("/tmp/dir"));

Directory structure is:

tmp/
 - dir/
    - a/
       - b/
          - c.txt

I try debug this with following results:

  1. I stop program in FileUtils before c.txt is deleted. if (!file.delete())
  2. File is present and I can rename it (it is not locked I guess then).
  3. file.delete() returns true, program continues a normal way (the file is still present, but now I can't rename it)
  4. I stop program before b/ directory is removed. if (!directory.delete())
  5. c.txt is still present in this directory and delete() on directory returns false and "Unable to delete directory /tmp/dir/a/b/" exception is thrown
  6. When program ends the file is removed, but b/, a/, dir/ directories are not.

Weird behavior for me is that c.txt file exists after deletion and invoking delete on his parent dir cause error then. The file is used only by Java program. Any suggestions? Any idea how to check in Java if some FileHandlers are still open for the file?

Update: fixed

I'm stupid jerk, I checked my code again and I found out that I miss close stream which previously read the file. I had a code for reading the input:

ByteArrayOutputStream baos = new ByteArrayOutputStream();
InputStream is = new FileInputStream(new File("/tmp/dir/a/b/c.txt"));
IOUtils.copy(is, baos); 
String content = new String(baos.toByteArray());

and I change to (it works now):

ByteArrayOutputStream baos = new ByteArrayOutputStream();
InputStream is = new FileInputStream(new File("/tmp/dir/a/b/c.txt"));
IOUtils.copy(is, baos);
// Close streams!
baos.flush();
baos.close();
is.close(); // This is the most important!
String content = new String(baos.toByteArray());

This is just example, I know that it is important to close all streams correctly (using try-finally). BufferedInputStream should be useful here too.

Answer