Java 中 file.exists() 的详细信息?

Details of file.exists() in Java?

我正在使用以下代码检查文件是否存在并且可以在 Java 中读取:

File sourceFile = new File(sourcePath);
if (!sourceFile.exists() || !sourceFile.canRead())
    throw new Exception("Source file is not accessible.");

但是,我要解决的问题是确定关于 为什么 exists() 可能会或可能不会 return 错误的更详细信息。例如,位置可能可访问,但文件不存在。或者,该位置可能被防火墙阻止并且文件确实存在,只是无法访问。

是否有快速的方法来确定:

谢谢!

File 你不能。

使用 Path,您可以:

thePath.getFileSystem().provider().checkAccess(thePath)

javadoc link.

下面exists方法和checkRead方法代码:

     public boolean exists() {
         SecurityManager security = System.getSecurityManager();
         if (security != null) {
             security.checkRead(path);
         }
         return ((fs.getBooleanAttributes(this) & FileSystem.BA_EXISTS) != 0);
     }

     public void checkRead(FileDescriptor fd) {
         if (fd == null) {
             throw new NullPointerException("file descriptor can't be null");
         }
         checkPermission(new RuntimePermission("readFileDescriptor"));
     }

现有方法正在执行文件检查读取。

请参考以下内容link,以便使用 SecurityManager

授予对给定文件的读取权限

https://docs.oracle.com/javase/8/docs/technotes/guides/security/permissions.html