2009-11-13 59 views
33
File file = new File(path); 
if (!file.delete()) 
{ 
    throw new IOException(
     "Failed to delete the file because: " + 
     getReasonForFileDeletionFailureInPlainEnglish(file)); 
} 

已经有很好的执行getReasonForFileDeletionFailureInPlainEnglish(file)了吗?否则我只需要自己写。如何判断文件删除在Java中失败的原因?

回答

-1

正如File.delete()

指出,你可以使用抛出exeception为您的SecurityManager。

3

缺失可能由于一个或多个原因:

  1. 文件不存在(使用File#exists()进行测试)。
  2. 文件被锁定的(因为它是由另一个应用程序(或您自己的代码打开!)。
  3. 您没有被授权(但会抛出一个SecurityException,不予退换假的!)。

因此,无论何时删除失败,请执行File#exists()以检查它是由1)还是2)引起的。

总结:

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 + "."); 
} 
+0

@BalusC,记得file.exists()还可以抛出SecurityException。 –

+0

如果由于文件系统权限而导致删除失败,则不会得到SecurityException。 – Thilo

+0

如果您的JVM配置受限,则只会得到SecurityException,例如,如果您是小程序。一个“正常”的应用程序不会在这里被沙箱化。 – Thilo

20

嗯,最好我能做到:

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."; 
    } 
} 
+0

@Cory,file.exists(),isDirectory()和list()都可以抛出SecurityExcepions。 –

+0

@Bob:只发生在沙箱中。原来的delete()很可能也会抛出SecurityException。但为了完整性,我想他应该抓住它(并返回“沙箱:没有文件系统访问”) – Thilo

+0

@Thilo补充说,但是,是的,我正在处理所问的问题,而不是所有其他参与文件I/O的可能性。 :) –

21

在Java 6中,不幸的是没有办法确定为什么一个文件无法删除。对于Java 7,您可以使用java.nio.file.Path#delete(),如果无法删除文件或目录,则会给出详细的失败原因。

请注意,file.list()可能会返回可以删除的目录条目。用于删除的API文档说只有空目录可以被删除,但是如果所包含的文件是例如文件,则目录被认为是空的。 OS特定的元数据文件。

+7

此删除方法似乎不存在于Java 7 API中。 [链接](http://download.oracle.com/javase/7/docs/api/java/nio/file/Path.html) 编辑:刚刚发现它现在在Files类中。 [链接](http://download.oracle.com/javase/7/docs/api/java/nio/file/Files.html) – RishiD

+0

当_a file_无法删除时它抛出吗?返回类型是无效的!它的文档不清楚。在这里问:http://stackoverflow.com/questions/19935624/java-nio-file-files-deletepath-path-void-return-type –

6

请注意,它可以是您自己的应用程序,可以防止文件被删除!

如果您以前写入文件并且没有关闭写入器,那么您正在锁定文件。

+2

当在Windows 7上使用Java 6进行测试时,我也遇到了读者的问题。我在关闭阅读器之前试图删除文件,但是失败了。 – Doppelganger

4

的Java 7个java.nio.file.Files也可用于类:

http://docs.oracle.com/javase/tutorial/essential/io/delete.html

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