[英]classLoader.getResource doesn't work in jar file
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:file:\\ 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. 我检查了所有其他问题,没有有用的信息。
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);
You can't create a File instance, because the only file you have is the JAR. 您无法创建File实例,因为您拥有的唯一文件是JAR。 That's why getResource() returns URL. 这就是getResource()返回URL的原因。 You can get stream by using URL.openStream() method to read contents. 您可以使用URL.openStream()方法来读取内容。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.