ClassLoader.getResource()不适用于.jar文件 [英] ClassLoader.getResource() doesn't work from .jar file

查看:663
本文介绍了ClassLoader.getResource()不适用于.jar文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码:

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

但是,一旦我的应用程序导出到 .jar,这就无效了 file。

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

推荐答案

您的\t正在编译为选项卡 - 您需要将其转义:

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

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...

事实上,我会用正斜杠来指定它。无论如何,这适用于基于Windows和Unix的操作系统,它也适用于jar文件。我突出显示双反斜杠的唯一原因是提高字符串转义点。试试这个:

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:

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

接下来,请确保您已获得完全正确的名称文件,包括案例。即使Windows文件系统通常不区分大小写,jar文件也是如此。如果它实际上是卡片而不是卡片或TRANS.png而不是trans.png,它将无效。

Next, make sure you've got the exact correct 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.

这篇关于ClassLoader.getResource()不适用于.jar文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆