Java File.delete() does not delete all files

时光总嘲笑我的痴心妄想 提交于 2019-12-01 19:15:54

It returns a boolean value, you should check that. From the JavaDoc:

Returns: true if and only if the file or directory is successfully deleted; false otherwise

You should check the value of the return and take action.

If it returns false it may well be that you do not have permission to delete the file.

In that case you can check whether the file is writeable by the application and if not attempt to make it writeable - again this returns a boolean. If successful you can try deleting again.

You could use a utility method:

private void deleteFile(final File f) throws IOException {
    if (f.delete()) {
        return;
    }
    if (!f.canWrite() && !f.setWritable(true)) {
        throw new IOException("No write permissions on file '" + f + "' and cannot set writeable.");
    }
    if (!f.delete()) {
        throw new IOException("Failed to delete file '" + f + "' even after setting writeable; file may be locked.");
    }
}

I would also take their advice in the JavaDoc:

Note that the Files class defines the delete method to throw an IOException when a file cannot be deleted. This is useful for error reporting and to diagnose why a file cannot be deleted.

Provided that you are using Java 7 that is. That method throws a number of exceptions that you can handle:

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);
}

Example taken from the Oracle tutorial page.

Forcing the garbage collector to run using System.gc(); made all the files deletable.

Make sure that you don't have any open stream like BufferedReader/Writer, FileReader/Writer etc. First close them, then you should be able to delete the file. One more point, E.g. if you open a BufferedReader via another reader like FileReader, you must close both of the readers seperately.

So instead of this:

BufferedReader reader = new BufferedReader(new FileReader(new File(filePath)););

do this:

BufferedReader bufferedReader = null;
FileReader fileReader = null;

try{
    fileReader = new FileReader(readFile);
    bufferedReader = new BufferedReader(fileReader);

}catch{...}

...

try {
    fileReader.close();
    bufferedReader .close();
    readFile.delete();
} catch (IOException e) {
    e.printStackTrace();
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!