getResourceAsStream返回null [英] getResourceAsStream returns null
问题描述
我从Java项目的已编译JAR中的包中加载文本文件。相关的目录结构如下:
/src/initialization/Lifepaths.txt
用于加载文件的代码是:
<$ c $ Lifetime $ {
public static void execute(){
System.out.println(Lifepaths.class.getClass()。
getResourceAsStream(/ initialization / Lifepaths.txt ));
私人生活路径(){}
//这是暂时的;最终将从
之外调用public static void main(String [] args){execute();}
}
无论我使用什么,打印输出总是会打印 我该如何解决这个问题? I'm loading a text file from within a package in a compiled JAR of my Java project. The relevant directory structure is as follows: null
。我不知道为什么上述不会工作,所以我也试过:
/ src / initialization / Lifepaths.txt
initialization / Lifepaths.txt
Lifepaths.txt
$ b 这些工作。 我 阅读 无数 问题到目前为止的话题,但没有一个是有帮助的 - 通常,他们只是说加载文件使用根路径,我已经在做。这个,或者只是从当前目录加载文件(只是加载文件名
),我也试过了。正在使用适当的名称将文件编译到适当位置的JAR中。
Lifepaths.class.getClass()。getResourceAsStream(...)
使用系统类加载器加载资源,显然会失败,因为它没有看到你的JARs
Lifepaths.class.getResourceAsStream(...)
使用加载Lifepaths类的同一个类加载器加载资源,并且它应该可以访问JAR中的资源/src/initialization/Lifepaths.txt
The code being used to load the file is:
public class Lifepaths {
public static void execute() {
System.out.println(Lifepaths.class.getClass().
getResourceAsStream("/initialization/Lifepaths.txt"));
}
private Lifepaths() {}
//This is temporary; will eventually be called from outside
public static void main(String[] args) {execute();}
}
The print out will always print null
, no matter what I use. I'm not sure why the above wouldn't work, so I've also tried:
"/src/initialization/Lifepaths.txt"
"initialization/Lifepaths.txt"
"Lifepaths.txt"
Neither of these work. I've read numerous questions so far on the topic, but none of them have been helpful - usually, they just say to load files using the root path, which I'm already doing. That, or just load the file from the current directory (just load filename
), which I've also tried. The file is being compiled into the JAR in the appropriate location with the appropriate name.
How do I solve this?
Lifepaths.class.getClass().getResourceAsStream(...)
loads resources using system class loader, it obviously fails because it does not see your JARs
Lifepaths.class.getResourceAsStream(...)
loads resources using the same class loader that loaded Lifepaths class and it should have access to resources in your JARs
这篇关于getResourceAsStream返回null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!