简体   繁体   中英

Relative resource paths in Java project in IntelliJ IDEA

I am trying to display an icon in my GUI by using a relative path, as in "display image from resources/image.png ". I have tried a million different ways to express this, but nothing works. This makes me think it's a problem with my IntelliJ IDEA settings or project structure. I have set up the "resources" folder as a "resources folder". I don't know what else it expects me to do.

How can I load an icon from a file using a relative path in a Java project within IntelliJ IDEA?

My project structure:

src/main/java/ <-- set as "sources" in IntelliJ
src/main/java/ui/ <-- contains classes for my GUI
src/main/resources/ <-- set as "resources" in IntelliJ. Contains images.

Edit: Able to use relative path to confirm that file is found, not able to load it as icon.

String path = "src/main/resources/image.png";
System.out.println(new File(path).exists()); <-- true

I've encountered this issue many times and what worked for me was using InputStream

InputStream is = Main.class.getClassLoader().getResourceAsStream("name_of_file.png");

Using InputStream will allow you read from various file types. Now to load in the icon you can do

Icon icon = new ImageIcon(ImageIO.read(is));

Resources are on classpath, not on filesystem path - which is taken relative from running directory, which is project directory when you are running it from idea. Usually you will distribute your aplication as jar, and this it is better to load resources from classpath. In zour case - from root 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