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
  • 3
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值