How to tell why a file deletion fails in Java?

前端 未结 6 1232
忘掉有多难
忘掉有多难 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:51

    Hmm, best I could do:

    public String getReasonForFileDeletionFailureInPlainEnglish(File file) {
        try {
            if (!file.exists())
                return "It doesn't exist in the first place.";
            else if (file.isDirectory() && file.list().length > 0)
                return "It's a directory and it's not empty.";
            else
                return "Somebody else has it open, we don't have write permissions, or somebody stole my disk.";
        } catch (SecurityException e) {
            return "We're sandboxed and don't have filesystem access.";
        }
    }
    

提交回复
热议问题