简体   繁体   English

使用可执行Jar访问文件

[英]Accessing File With Executable Jar

I am getting a file like so: 我得到的文件是这样的:

File testHeaderFile = new File(ClassLoader.getSystemResource("Images/redHeader.jpg").toURI());

This works when I compile in eclipse, but not when I run from an executable jar. 当我在eclipse中编译时,此方法有效,但是当我从可执行jar运行时,则无效。

This code is working with the jar: 这段代码与罐子一起工作:

ImageIcon pc = new ImageIcon(getClass().getClassLoader().getResource("Images/stateFarmTheme1Icon.png"));

What am I doing wrong exactly? 我到底在做什么错?

Every class loader has itself search paths. 每个类加载器都有自己的搜索路径。

ClassLoader.getSystemResource: Just find a resource of the specified name from the search path(include project directory in eclipse) used to load classes and locate the resource through the system class loader.so,does not include executable jar directory. ClassLoader.getSystemResource:只需从搜索路径中找到指定名称的资源(在eclipse中包含项目目录),该资源用于加载类并通过系统类loader.so找到该资源,因此不包含可执行jar目录。

getClass().getClassLoader().getResource: This method will first search the parent class loader for the resource; getClass()。getClassLoader()。getResource:此方法将首先在父类加载器中搜索资源; if the parent is null,the path of the class loader built-in to the virtual machine is searched.so,include executable jar directory. 如果父级为null,则搜索虚拟机内置的类加载器的路径。因此,包括可执行jar目录。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM