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

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

猜你喜欢

转载自blog.csdn.net/ll413343176/article/details/84059549
今日推荐