eclipse classLoader.getResource 在 jar 文件中不起作用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26675048/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-19 22:09:03  来源:igfitidea点击:

classLoader.getResource doesn't work in jar file

javaeclipse

提问by Insignificant Person

ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
URL url = classLoader.getResource("com/x/y/z.cfg");
File file = new File(url.getPath());

This works when running jar file from Eclipse but not works when running in a jar file.

这在从 Eclipse 运行 jar 文件时有效,但在 jar 文件中运行时无效。

java.io.FileNotFoundException: file:\C:\Users\nova\Desktop\Matcher.jar!\c om\x\y\z.cfg

java.io.FileNotFoundException: 文件:\C:\Users\nova\Desktop\Matcher.jar!\c om\x\y\z.cfg

This is not a duplicate.I've checked all other questions, no useful information.

这不是重复的。我已经检查了所有其他问题,没有有用的信息。

回答by Braj

When file is bundled inside the jar then it become byte stream instead of a normal File object.

当文件捆绑在 jar 中时,它会变成字节流而不是普通的 File 对象。

Try

尝试

InputStream stram=getClass().getClassLoader().getResourceAsStream(relativePath);

More Tutorial...

更多教程...

Read similar post hereand here

在这里这里阅读类似的帖子

回答by McMonster

You can't create a File instance, because the only file you have is the JAR. That's why getResource() returns URL. You can get stream by using URL.openStream() method to read contents.

您无法创建 File 实例,因为您拥有的唯一文件是 JAR。这就是 getResource() 返回 URL 的原因。您可以通过使用 URL.openStream() 方法读取内容来获取流。