【发布时间】:2018-07-29 08:23:41
【问题描述】:
我的项目的src/main/resources 文件夹中有一个文件watstheday.txt,如下图所示。
我通过ClassLoader 的getResourceAsStream() 方法读取了文件,并在我的代码中执行了进一步的操作,该代码运行良好。
但是,如果我尝试通过以下代码检查文件是否存在,它总是返回 false。
try {
ClassLoader classLoader = getClass().getClassLoader();
System.out.println("!@#!@# so difficult to be simple..."+classLoader.getResource("watstheday.txt"));
//this returns false but the file is there
System.out.println("@#@ vertigo2 "+new File(classLoader.getResource("watstheday.txt").getFile()).isFile());
//this ALSO returns false but the file is there
System.out.println("@#@ vertigo2 "+new File(classLoader.getResource("watstheday.txt").getFile()).exists());
//Giving the / to mark the root of the application though that's not required
System.out.println("@#@ vertigo3 "+new File(classLoader.getResource("//watstheday.txt").getFile()).isFile());
//the below code with getResourceAsStream works absolutely fine and i can read the file
classLoader.getResourceAsStream("watstheday.txt");
BufferedReader buf = new BufferedReader(
new InputStreamReader(classLoader.getResourceAsStream("watstheday.txt")));
while (true) {
lineJustFetched = buf.readLine();
System.out.println(" @@#@ lineJustFetched =" + lineJustFetched);
}
buf.close();
} catch (Exception e) {
e.printStackTrace();
}
我在最终提出这个问题之前咨询了followingposts,但找不到我做错了什么。当我打印文件名时,它会打印出完整的部署路径,显示为
!@#!@# so difficult to be simple... vfs=$my_server_deployment_folder_location$/helloworld/watstheday.txt
【问题讨论】:
-
您的文件是否可能存在于 zip 文件中?
-
仅供参考,我在我的 Eclipse 上测试了你的代码并得到了@#@ vertigo2 true @#@ vertigo2 true
-
阅读这篇文章,这解释了为什么
getResource(...).getFile()没有返回可以传递给java.io.File构造函数的东西,因为它不是一回事:What's the difference between a Resource, URI, URL, Path and File in Java? -
File.exists() 如果您的文件作为实体物理存在,则返回 true。在虚拟文件系统上时它总是返回 false。
-
@EvgeniyDorofeev 我反复尝试过,但对我来说不是这样。我看不到自己的愚蠢,????
标签: java file-io getresource