java读取文件 classpath_如何真正从Java的classpath中读取文本文件

通过类path中的目录,从同一个类加载器加载的类中,您应该可以使用以下任一项:

// From ClassLoader, all paths are "absolute" already - there's no context // from which they could be relative. Therefore you don't need a leading slash. InputStream in = this.getClass().getClassLoader() .getResourceAsStream("SomeTextFile.txt"); // From Class, the path is relative to the package of the class unless // you include a leading slash, so if you don't want to use the current // package, include a slash like this: InputStream in = this.getClass().getResourceAsStream("/SomeTextFile.txt");

如果这些不起作用,那表明其他的东西是错的。

所以举个例子,拿这个代码:

package dummy; import java.io.*; public class Test { public static void main(String[] args) { InputStream stream = Test.class.getResourceAsStream("/SomeTextFile.txt"); System.out.println(stream != null); stream = Test.class.getClassLoader().getResourceAsStream("SomeTextFile.txt"); System.out.println(stream != null); } }

而这个目录结构:

code dummy Test.class txt SomeTextFile.txt

然后(使用Unixpath分隔符,因为我在Linux上):

java -classpath code:txt dummy.Test

结果:

true true

当使用Spring框架(作为实用程序或容器的集合 – 你不需要使用后者的function),你可以很容易地使用资源抽象。

Resource resource = new ClassPathResource("com/example/Foo.class");

通过资源接口,您可以

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值