java ClassLoader.getResource() 不适用于 .jar 文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1664073/
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-10-29 17:29:30  来源:igfitidea点击:

ClassLoader.getResource() doesn't work from .jar file

javaimagejar

提问by Patrick

I have the following code:

我有以下代码:

private final ImageIcon placeHolder = new ImageIcon(this.getClass().getClassLoader().getResource("Cards\trans.png"));

But this does not work once my application exported into a .jarfile.

但是一旦我的应用程序导出到.jar文件中,这将不起作用。

回答by Jon Skeet

Your "\t" is being compiled as a tab - you need to escape it:

您的 "\t" 正在编译为选项卡 - 您需要对其进行转义:

private final ImageIcon placeHolder = new ImageIcon(
    this.getClass().getClassLoader().getResource("Cards\trans.png"));

Note the double backslash. This may not be the only thing wrong, of course - but it's a start...

注意双反斜杠。当然,这可能不是唯一的错误——但这是一个开始......

In fact, I would specify it with a forward slash instead. That works on both Windows and Unix-based OSes anyway, and it also works with jar files. The only reason I highlighted the double backslash was to raise the point of string escaping in general. Try this:

事实上,我会用正斜杠来指定它。无论如何,这适用于基于 Windows 和 Unix 的操作系统,并且它也适用于 jar 文件。我强调双反斜杠的唯一原因是为了提高字符串转义的重要性。试试这个:

private final ImageIcon placeHolder = new ImageIcon(
    this.getClass().getClassLoader().getResource("Cards/trans.png"));

Next, make sure you've got the exactcorrect name for the file, including case. Even though Windows file systems aren't generally case-sensitive, jar files are. If it's actually "cards" instead of "Cards" or "TRANS.png" instead of "trans.png", it won't work.

接下来,确保您获得了完全正确的文件名称,包括大小写。尽管 Windows 文件系统通常不区分大小写,但 jar 文件是。如果它实际上是“卡片”而不是“卡片”或“TRANS.png”而不是“trans.png”,则它将不起作用。

回答by Basil

Use this for getting images in jar file

使用它来获取 jar 文件中的图像

ClassLoader.getSystemResource("images/Springz3.png"));

ClassLoader.getSystemResource("images/Springz3.png"));