file.delete() returning false even file is writable

1.3k views Asked by At

I'am trying to copy a file to a directory and then deleting it, but file.delete() keeps returning false

Here is my code:

for (File file : list) {
            if (!file.isDirectory()) {
                try {
                    FileUtils.copyFileToDirectory(file, path);
                    file.setWritable(true);                         
                    System.out.println(file.delete());
                    if(file.exists()){
                        file.deleteOnExit();
                    }
                } catch (IOException e) {
                    System.out.println(e);
                }
            }
        }
1

There are 1 answers

0
nagendra547 On BEST ANSWER

Few ideas that you can work it out.

  • If you want to delete file first close all the connections and streams. after that delete the file
  • Make sure you have the delete permissions for the file
  • Make sure you are in right directory. Try using absolute path for deleting the file, in case delete is not working. Path might not be correct for the file.
  • Use Files.delete. The delete(Path) method deletes the file or throws an exception if the deletion fails. For example, if the file does not exist a NoSuchFileException is thrown. You can catch the exception to determine why the delete failed as follows: See Oracle docs here

    try {
        Files.delete(path);
    } catch (NoSuchFileException x) {
        System.err.format("%s: no such" + " file or directory%n", path);
    } catch (DirectoryNotEmptyException x) {
        System.err.format("%s not empty%n", path);
    } catch (IOException x) {
        // File permission problems are caught here.
        System.err.println(x);
    }