从 jar 访问 jar 外的资源

Access a resource outside a jar from the jar

我正在尝试从 jar 文件访问资源。资源位于与 jar 相同的目录中。

my-dir:
 tester.jar
 test.jpg

我尝试了不同的方法,包括以下,但每次输入流都是空的:

[1]

String path = new File(".").getAbsolutePath();
InputStream inputStream = this.getClass().getResourceAsStream(path.replace("\.", "\") + "test.jpg");

[2]

File f = new File(this.getClass().getProtectionDomain().getCodeSource().getLocation().toURI().getPath());
InputStream inputStream = this.getClass().getResourceAsStream(f.getParent() + "test.jpg");

你能给我一些提示吗?谢谢

如果您确定您的应用程序的当前文件夹是 jar 的文件夹,您可以简单地调用 InputStream f = new FileInputStream("test.jpg");

getResource 方法将使用类加载器加载内容,而不是通过文件系统。这就是您的方法 (1) 失败的原因。

如果包含您的 *.jar 和图像文件的文件夹在类路径中,您可以像在默认包中一样获取图像资源:

class.getClass().getResourceAsStream("/test.jpg");

注意:图像现在已加载到类加载器中,只要应用程序运行,图像就不会卸载并在您再次加载时从内存中提供。

如果类路径中没有给出包含jar 文件的路径,您获取jar 文件路径的方法很好。 但随后只需通过 URI 直接访问该文件,方法是在其上打开一个流:

URL u = this.getClass().getProtectionDomain().getCodeSource().getLocation();
// u2 is the url derived from the codesource location
InputStream s = u2.openStream();

使用this tutorial 帮助您创建一个URL 到一个jar 文件中的单个文件。

这是一个例子:

String jarPath = "/home/user/myJar.jar";
String urlStr = "jar:file://" + jarPath + "!/test.jpg";
InputStream is = null;
try {
    URL url = new URL(urlStr);
    is = url.openStream();
    Image image = ImageIO.read(is);
}
catch(Exception e) {
    e.printStackTrace();
}
finally {
    try {
        is.close();
    } catch(Exception IGNORE) {}
}