1

I am trying to delete the content of the directory with few files, and I am not able to delete it. When I tried the methods .delete() it returns a false, but .canWrite(), .canRead() method returns true for the code.

My file path in the system is:

E:\PROJECT01022012\.metadata\.plugins\org.eclipse.wst.server.core\tmp4\wtpwebapps\realmap\PHOTO\VFIN5CT5651842012\Inspirational-GravityHighRes.jpg

I tried this and this but no luck.

public static boolean removeDirectory(File directory){

 if (directory.isDirectory())
    {
     File[] fls=directory.listFiles();

     for (int i = 0; i < fls.length; i++) {
          fls[i].delete();

     }
     } 

}
Community
  • 1
  • 1
arjuncc
  • 3,227
  • 5
  • 42
  • 77

2 Answers2

2

You cannot delete a file if it's already been opened elsewhere. E.g. in Java by an FileInputStream or FileOutputStream which isn't been closed, or outside Java's context in enduser's image viewer/editor or so.

In Java side, make sure that you aren't opening the file anywhere. Make sure that any FileInputStream and FileOutputStream on that file is been close()d in finally block after use. Make sure that the enduser itself isn't opening the picture in some image viewer/editor.

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
0

Maybe your files in directory is read only? If yes, you can try setReadOnly(false) - but I remember that does not work. It is actually does not reset read only flag from file. Well, some work around can be call of Runtime.exec with command to delete your files for your OS:

// For windows - option /F to force delete read-only files:
Runtime.getRuntime().exec("DEL /F E:\PROJECT01022012\.metadata\.plugins" +
    "\org.eclipse.wst.server.core\tmp4\wtpwebapps\realmap\PHOTO\VFIN5CT5651842012" +
    "\Inspirational-GravityHighRes.jpg");
alexey28
  • 5,170
  • 1
  • 20
  • 25