[英]class.getClassLoader getResourceasStream returns null in jar
I am facing this strange issue while building my project through Maven. 通过Maven构建项目时,我面临着这个奇怪的问题。
Here is my code for reading the text file, which I have put under resources
folder in a Maven project. 这是我读取文本文件的代码,该文件已放在Maven项目的
resources
文件夹下。 While Running from IDE everything is fine but once I create a jar and run from command line, it is returning me null
. 从IDE运行时,一切都很好,但是一旦我创建了jar并从命令行运行,它就会返回
null
。
public static void main(String[] args) throws IOException {
URL jarUrl = FreeCalcTest.class.getProtectionDomain().getCodeSource().getLocation();
System.out.println("JarUrl : "+jarUrl);
String filePath = "UserDetails\\ReadFile.txt";
URL url = FreeCalcTest.class.getClassLoader().getResource(filePath);
System.out.println(url);
InputStream inputStream = FreeCalcTest.class.getClassLoader().getResourceAsStream(filePath);
UserDetailReader userDetailReader = new UserDetailReader(inputStream);
List<UserDetailValueSet> userDetails = userDetailReader.read();
Set<String> attrList = UserDetailAttributes.getAttributes();
Iterator<String> attrItr = attrList.iterator();
Iterator<UserDetailValueSet> itr = userDetails.iterator();
while (itr.hasNext()) {
UserDetailValueSet userDetailValueSet = (UserDetailValueSet) itr.next();
while (attrItr.hasNext()) {
String attr = (String) attrItr.next();
System.out.println(userDetailValueSet.getValueSet().get(attr));
}
}
}
Exception stacktrace: 异常stacktrace:
JarUrl : file:/C:/Users/bnath/Desktop/FreeCalc-0.0.1-SNAPSHOT.jar null
Exception in thread "main" java.lang.NullPointerException
at java.io.Reader.<init>(Unknown Source) at java.io.InputStreamReader.<init>(Unknown Source)
at com.sec.io.reader.UserDetailReader.read(UserDetailReader.java:24)
at com.sec.testFreeCalc.FreeCalcTest.main(FreeCalcTest.java:24)
You should use a forward slash as separator for resource paths, therefore try "UserDetails/ReadFile.txt"
您应使用正斜杠作为资源路径的分隔符,因此请尝试
"UserDetails/ReadFile.txt"
The classloader is responsible to interpret the path and find the resource. 类加载器负责解释路径并找到资源。 When searching for a resource in the filesystem a path with a backslash seems to work in Windows, probably because it is simple interpreted as relative path.
在文件系统中搜索资源时,在Windows中似乎可以使用带反斜杠的路径,这可能是因为它很容易解释为相对路径。
Such a path does not work when resources inside a JAR file are requested since the format for JAR entries requires the forward slash as separator char. 当请求JAR文件中的资源时,这样的路径不起作用,因为JAR条目的格式要求使用正斜杠作为分隔符char。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.