I made an application that uses several images. I have 2 ways to run my app:
- press run
in idea
- make a fat jar file and run it from console java -jar app.jar
If I want to run it from Idea
I have to use:
BufferedImage backgroundImage = ImageIO.read(new File("res/field.png"));
instead of
BufferedImage backgroundImage = ImageIO.read(getClass().getClassLoader().getResource("res/field.png"));
<- that's what I have to use in jar file case
Why? I thought that they're about the same. Is there any universal way for my case?
I always use:
BufferedImage backgroundImage = ImageIO.read(getClass().getResource("res/field.png"));
which works from both the IDE and from inside a jar. .getResource(...) returns an URL, either jar:// or file://
Just be aware, the path either starts with a / (in which case it is relative to the package root) or it is relative to the class package - if your class is com.example.Test, /res/
refers to the folder com/example/Test/res/.
You can even use the static version - YourClassName.class.getResource(...) which allow you to easily reach other "branches" of your package tree (you can use reference is from classes located in different branches)
With java.io
, the relative path is dependent on the current working directory.
With getResource you must have that resource in the classpath
.