无法通过URL访问.jar中的文件 [英] Can't access file in .jar via URL

查看:228
本文介绍了无法通过URL访问.jar中的文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要使用URL访问当前执行的.jar中的文件。

I need to access a file inside the currently executed .jar using a URL.

URL url = BlockConverter.class.getResource("/test.txt");
System.out.println(url.toString());
InputStream  is = url.openStream();

这就是我所做的。
输出为:

This is what I did. The output is:

jar:file:/C:/Users/User/Desktop/SERVER/plugins/MyJar.jar!/test.txt

我的InputStream在初始化时总是会抛出IOException,甚至虽然URL正确输出。
那怎么可能呢?
为什么我不能打开流?

My InputStream always ends up throwing an IOException when being initialized, even though the URL is being output correctly. So how is that possible? Why can't I open the stream?

编辑:
另外,请不要回答使用getResourceAsStream,因为它使用相同类型的代码:

Also, please don't answer with "use getResourceAsStream", since it uses the same kind of code:

public InputStream getResourceAsStream(String name) {
    URL url = getResource(name);
    try {
        return url != null ? url.openStream() : null;
    } catch (IOException e) {
        return null;
    }
}


推荐答案

我会直接将它作为流打开例如

I would open it as a stream directly e.g.

InputStream  is = BlockConverter.class.getResourceAsStream("/test.txt");

上面的方法是我通常访问jar中的资源的方式(它将打开资源而不管它被打包在一个jar中,或者只是作为一个未打包的部署,请注意)

The above method is the way I normally access resources within a jar (it will open the resource regardless of it being packaged within a jar, or simply as an unpackaged deployment, note)

这篇关于无法通过URL访问.jar中的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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