java 中文路径 找不到文件路径,如何从Java项目中的相对路径读取文件? java.io.File找不到指定的路径...
I have a project with 2 packages:tkorg.idrs.core.searchenginestkorg.idrs.core.searchenginesIn package (2) I have a text file ListStopWords.txt, in package (1) I have a class FileLoadder. Here is code
I have a project with 2 packages:
tkorg.idrs.core.searchengines
tkorg.idrs.core.searchengines
In package (2) I have a text file ListStopWords.txt, in package (1) I have a class FileLoadder. Here is code in FileLoader:
File file = new File("properties\\files\\ListStopWords.txt");
But have this error:
The system cannot find the path specified
Can you give a solution to fix it? Thanks.
解决方案
If it's already in the classpath, then just obtain it from the classpath. Don't fiddle with relative paths in java.io.File. They are dependent on the current working directory over which you have totally no control from inside the Java code.
Assuming that ListStopWords.txt is in the same package as FileLoader class:
URL url = getClass().getResource("ListStopWords.txt");
File file = new File(url.getPath());
Or if all you're after is an InputStream of it:
InputStream input = getClass().getResourceAsStream("ListStopWords.txt");
If the file is -as the package name hints- is actually a fullworthy properties file (containing key=value lines) with just the "wrong" extension, then you could feed it immediately to the load() method.
Properties properties = new Properties();
properties.load(getClass().getResourceAsStream("ListStopWords.txt"));
Note: when you're trying to access it from inside static context, then use FileLoader.class instead of getClass() in above examples.
魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。
更多推荐


所有评论(0)