从jar访问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和image文件的文件夹位于类路径中,则可以像在default-package上一样获取图像资源:

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

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

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

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

使用本教程可帮助您创建jar文件中单个文件的URL。

这是一个例子:

 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) {} }