Java File、Paths、Path的意外错误:file.exists() 结果错误

本文探讨了在Java中使用Path和File类进行文件操作时遇到的奇怪现象,即Path对象的toFile()方法结合exists()判断文件存在性时出现的矛盾结果。作者最终通过直接使用字符串路径解决问题,但仍对原理感到困惑。

最近做项目自己写文件上传和下载,用到了File、Paths、Path,其中出现了如下意外情况:

实例化Path:

Path path = Paths.get("E://souces/tmp/abc");

将此path作为入参:

test(path);

test方法内调用:

       

if(path.toFile().exists()){
    System.out.print("file is exists");
    // TODO 接收流并写入文件

}

输出:

file is exists

然而,在接下来以path作为目录将流写入文件(文件流会自动创建文件)时,抛错:文件路径不存在!

我去看了目录,这个路径确实不存在;但是有意思的是, path.toFile().exists() 返回的是 true.

这种问题让我很苦恼,后来我去看了File、Paths、Path这些类,但都没能找出原因,百度也未果,目前只能猜测这可能是有关内存和jvm中的一个未知bug。如果哪位大牛知道原因还望不吝赐教,笔者感激不尽。

然后偶只好放弃使用Path,直接传入路径字符串

File file = new File(pathStr);

if(file.exists()){

    System.out.print("file is exists");

    // TODO 接收流并写入文件

}

然后这样做终于没问题了。

虽然coding已经结束,但是关于上述问题,“Paths实例得到文件对象(toFile()),调用exists()方法判断路径是否存在,执行结果错误”,我仍会保留疑问,期望各位大牛不吝解惑,谢谢。

ZhaoCong-iMac:release zhaocong$ /Users/zhaocong/Qt5.9.6/5.9.6/clang_64/bin/macdeployqt ./HATMiniPlayer.app ERROR: no file at "/usr/lib/libHATUILib.1.dylib" File exists, skip copy: "HATMiniPlayer.app/Contents/PlugIns/platforms/libqcocoa.dylib" File exists, skip copy: "HATMiniPlayer.app/Contents/PlugIns/printsupport/libcocoaprintersupport.dylib" File exists, skip copy: "HATMiniPlayer.app/Contents/PlugIns/imageformats/libqgif.dylib" File exists, skip copy: "HATMiniPlayer.app/Contents/PlugIns/imageformats/libqicns.dylib" File exists, skip copy: "HATMiniPlayer.app/Contents/PlugIns/imageformats/libqico.dylib" File exists, skip copy: "HATMiniPlayer.app/Contents/PlugIns/imageformats/libqjpeg.dylib" File exists, skip copy: "HATMiniPlayer.app/Contents/PlugIns/imageformats/libqmacjp2.dylib" File exists, skip copy: "HATMiniPlayer.app/Contents/PlugIns/imageformats/libqsvg.dylib" File exists, skip copy: "HATMiniPlayer.app/Contents/PlugIns/imageformats/libqsvg_debug.dylib" File exists, skip copy: "HATMiniPlayer.app/Contents/PlugIns/imageformats/libqtga.dylib" File exists, skip copy: "HATMiniPlayer.app/Contents/PlugIns/imageformats/libqtiff.dylib" File exists, skip copy: "HATMiniPlayer.app/Contents/PlugIns/imageformats/libqwbmp.dylib" File exists, skip copy: "HATMiniPlayer.app/Contents/PlugIns/imageformats/libqwebp.dylib" File exists, skip copy: "HATMiniPlayer.app/Contents/PlugIns/iconengines/libqsvgicon.dylib" WARNING: WARNING: "HATMiniPlayer.app/Contents/Resources/qt.conf" already exists, will not overwrite. WARNING: To make sure the plugins are loaded from the correct location, WARNING: please make sure qt.conf contains the following lines: WARNING: [Paths] WARNING: Plugins = PlugIns ZhaoCong-iMac:release zhaocong$
09-16
评论 1
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值