从jar访问jar外的资源

编程入门 行业动态 更新时间:2024-10-25 23:27:11
本文介绍了从jar访问jar外的资源的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

I'm trying to access a resource from a jar file. The resource is located in the same directory where is the jar.

my-dir: tester.jar test.jpg

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

I tried different things including the following, but every time the input stream is null:

[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");

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

Can you give me some hints? Thanks.

推荐答案

如果您确定,您的应用程序的当前文件夹是jar的文件夹,您只需调用 InputStream f = new FileInputStream(test.jpg);

If you are sure, that your application's current folder is the folder of the jar, you can simply call InputStream f = new FileInputStream("test.jpg");

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

The getResource methods will load stuff using the classloader, not through filesystem. This is why your approach (1) failed.

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

If the folder containing your *.jar and image file is in the classpath, you can get the image resource as if it was on the default-package:

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

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

Beware: The image is now loaded in the classloader, and as long as the application runs, the image is not unloaded and served from memory if you load it again.

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

If the path containing the jar file is not given in the classpath, your approach to get the jarfile path is good. But then simply access the file directly through the URI, by opening a stream on it:

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

更多推荐

从jar访问jar外的资源

本文发布于:2023-10-07 17:38:35,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1470055.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:资源   jar

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!