简体   繁体   English

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

[英]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);

More Tutorial... 更多教程......

Read similar post here and here 在这里这里阅读类似的帖子

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.

相关问题 ClassLoader.getResource()在.jar文件中不起作用 - ClassLoader.getResource() doesn't work from .jar file ClassLoader.getResource()对jar中的图标文件不起作用。 图标必须存在于包含jar的文件夹中 - ClassLoader.getResource() doesn't work for the icon files in a jar. The icons need to be present in the folder containing jar classloader.getResource返回带有war文件的路径 - classloader.getResource return a path with war file Class.getResource()和ClassLoader.getResource()在可执行jar中的奇怪行为 - Strange behavior of Class.getResource() and ClassLoader.getResource() in executable jar NullPointerException on ClassLoader.getResource() - NullPointerException on ClassLoader.getResource() classLoader.getResource(“。”)是/ bin文件夹 - classLoader.getResource(“.”) is /bin folder 使用ClassLoader.getResource()加载BufferedImage - loading BufferedImage with ClassLoader.getResource() 无法使用classLoader.getResource(fileName).getFile()获取文件 - unable to get file using classLoader.getResource(fileName).getFile() ClassLoader.getResource在使用File.getAbsolutePath时返回null - ClassLoader.getResource returning null while using File.getAbsolutePath classLoader.getResource(filename) 不返回现有文件(返回 null) - classLoader.getResource(filename) not returning existent file (returning null)
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM