简体   繁体   中英

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.

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.

getClass().getClassLoader().getResource: This method will first search the parent class loader for the resource; if the parent is null,the path of the class loader built-in to the virtual machine is searched.so,include executable jar directory.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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