java resources感叹号,无法在以感叹号结尾的目录中打开资源(!)

当从带有感叹号的目录启动Java可执行jar时,getResourceAsStream()方法返回null。问题源于jar URL中'!'字符的特殊含义,导致路径解析错误。此问题已存在多年且未修复。解决方案是避免在目录名中使用感叹号。
摘要由CSDN通过智能技术生成

The getResourceAsStream-method returns null whenever running the executable jar in a directory which ends with a exclamation mark.

For the following example, I have a Eclipse project the following directory structure:

src\ (Source Folder)

main\ (Package)

Main.java

res\ (Source Folder)

images\

Logo.png

I'm reading the Logo.png as follows:

public static void main(String[] args) throws IOException {

try (InputStream is = Main.class.getClassLoader().getResourceAsStream("images/Logo.png")) {

Image image = ImageIO.read(is);

System.out.println(image);

}

}

See the attachment for 2 test cases. First, the executable jar is started from the directory "D:\test123!@#" without any problems. Secondly, the executable jar is started from the directory "D:\test123!@#!!!", with problems.

Are directories ending with an exclamation mark not supported? Is the code wrong?

Thanks in advance.

p0N83.png

解决方案

Probably because of this bug or any of the many similar bugs in the Java bug database:

The reason is that "!/" in a jar URL is interpreted as the separator between the JAR file name and the path within the JAR itself. If a directory name ends with !, the "!/" character sequence at the end of the directory is incorrectly interpreted. In your case, you are actually trying to access a resource with the following URL:

jar:file:///d:/test1231@#!!!/test.jar!/images/Logo.png

The bug has been open for almost 12 years and is not likely to be fixed. Actually I don't know how it can be fixed without breaking other things. The problem is the design decision to use ! as a character with a special meaning (separator) in the URL scheme for JAR files:

jar:!/

Since the exclamation mark is an allowed character in URLs, it may occur both in the URL to the JAR file itself, as well as in the path within the JAR file, making it impossible in some cases to find the actual "!/" separator.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值