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
classLoader.getResource doesn't work in jar file
提问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
回答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() 方法读取内容来获取流。