java.io.File.exists在文件存在时返回false的BUG

java.io.File.exists在文件存在时返回false的BUG

在工作上有遇到一个情况,在多服务器情况下将文件挂载于其他服务器,A服务器将文件保存到文件服务器了,B服务器需要去下载文件但是调用file.exists()方法却显示不存在,导致失败。

原因

在Oracle Java Bug Databse上发现了有人在2004年的1.4.2版本的Java就发现了相同的问题,他看了源码后发现是因为File.exists其实是用了Linux的stat(2)命令,如果这个命令失败了,File.exists就认为是文件不存在。

A DESCRIPTION OF THE PROBLEM : When operating on NFS-mounted volumes, java.io.File.exists will sometimes return “false” even though the file referenced actually does exist. The actual problem is a stale NFS file handle, which can occur for a number of reasons. An examination of the java source code shows that File.exists ends up performing a stat(2). If the stat fails, then File.exists assumes that the file being stat’ed does not exist. This is a false assumption. stat(2) can fail for several reasons other than ENOENT. One such “other” error is ESTALE, which is what I get if I use JNI to perform a “native” stat(2) on the same file that File.exists claims does not exist. STEPS TO FOLLOW TO REPRODUCE THE PROBLEM : I do not have a simple method for reproducing this problem, however an examination of the java sources will bear out my explantion above. EXPECTED VERSUS ACTUAL BEHAVIOR : EXPECTED - If the file exists, I expect java.io.File.exists to return “true” ACTUAL - java.io.File.exists returns “false” occasionally. REPRODUCIBILITY : This bug can be reproduced occasionally. (Incident Review ID: 191975)

下面的回复:

EVALUATION The error code should be examined from the stat. But exists does not throw IOException so what to do in such a case would have to be determined. ###@###.### 2004-03-24 Submitter is correct but this API is too limited to do anything useful when the stat returns a real error. We will try to address this issue in JSR203. ###@###.### 2004-03-25

最后这个BUG的解决方案是不会修复 [○・`Д´・ ○]

解决方案

在尝试了网上找的各种的方法后都没有用,然后自己就想着看看到底是哪一个路径开始找不到,就发现一种方法可以让文件被检测到办法:如果文件不存在但是父目录存在时,获取父目录的下的文件,这时候file.exists()返回的就是True了!

File file = new File(path);
File parent = file.getParentFile();
// 文件不存在但是父目录存在时,获取父目录下的文件
if(!file.exists() && parent.exists()){
          
   
	File[] fileArray = parent.listFiles();
}

资料

    https://bugs.java.com/bugdatabase/view_bug.do?bug_id=5003595
经验分享 程序员 微信小程序 职场和发展