How to tell why a file deletion fails in Java?

前端 未结 6 1233
忘掉有多难
忘掉有多难 2020-11-27 21:13
File file = new File(path);
if (!file.delete())
{
    throw new IOException(
        \"Failed to delete the file because: \" +
        getReasonForFileDeletionFailur         


        
6条回答
  •  夕颜
    夕颜 (楼主)
    2020-11-27 21:52

    A deletion may fail due to one or more reasons:

    1. File does not exist (use File#exists() to test).
    2. File is locked (because it is opened by another app (or your own code!).
    3. You are not authorized (but that would have thrown a SecurityException, not returned false!).

    So whenever deletion fails, do a File#exists() to check if it is caused by 1) or 2).

    Summarized:

    if (!file.delete()) {
        String message = file.exists() ? "is in use by another app" : "does not exist";
        throw new IOException("Cannot delete file, because file " + message + ".");
    }
    

提交回复
热议问题