java 中文路径 找不到文件路径,如何从Java项目中的相对路径读取文件? java.io.File找不到指定的路径...

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.

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值