从jar访问jar外部的资源

mdp*_*mdp 9 java inputstream getresource

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

my-dir:
 tester.jar
 test.jpg
Run Code Online (Sandbox Code Playgroud)

我尝试了不同的东西,包括以下内容,但每次输入流为空时:

[1]

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

[2]

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

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

ths*_*hst 8

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

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

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

class.getClass().getResourceAsStream("/test.jpg");
Run Code Online (Sandbox Code Playgroud)

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

如果在类路径中没有给出包含jar文件的路径,那么获取jarfile路径的方法是好的.但是,然后直接通过URI访问该文件,方法是在其上打开一个流:

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