File.exists() returns false when file exists

借用了下stackoverflow上的标题名,方便需要的同学搜索 - -!

 

原文地址:https://blog.csdn.net/ll413343176/article/details/84059549  转载请注明

 

英语能力强的可以先看下这两个帖子

https://stackoverflow.com/questions/919918/file-exists-returns-false-when-file-exists

https://bugs.java.com/bugdatabase/view_bug.do;:YfiG?bug_id=4483097

使用相对路径时,如果user.dir发生变化会导致下面两个结果运行不一致

file.exists() == false

file.getAbsoluteFile().exists() == true

 

来自oracle官网的解释为:

EVALUATION

 

Not a bug.  If you need to resolve a filename against the value of

the "user.dir" system property then you must use getAbsolutePath (or

getAbsoluteFile, or getCanonicalPath, or getCanonicalFile).  Simpler

operations such as exists() always resolve against the directory in

which the Java virtual machine was originally invoked (and no, there

is no way to change that).

 

通过讨论与测试,理解结论为:

定义一个File时,若使用相对路径,则会因为user.dir发生改变时,调用file的getAbsxxx方法,会根据user.dir最新定义的位置改变

 

所以,在操作文件时,一定要使用绝对路径定义,防止文件指向存在歧义。例子如下

File file = new File(new File(".").getAbsolutePath(),"test.txt");

File file = new File("test.txt").getAbsoluteFile();

 

聊天记录微信已收藏,标签 File

 

具体理解过程如下:

 

那么,还有一个问题,相对路径file.exists()指向的文件具体在哪呢,为此,把文件改成一个特殊的文件名,

判断文件不存在时,进行新建,通过全盘搜索工具everything,查找文件所在位置,可以看到文件在当前工程目录之下。

回想一下,平常写代码时,特别是runnable jar,不都是使用相对路径,然后把文件放到jar同级目录么,此时程序内部若出现

System.setProperty("user.dir", "e:/");

f.getAbsolutePath();

相关代码,那么恭喜你,成功入坑。

 

 

  • 3
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值