Using URL or File (in ImageIO.read)

2019-04-17 00:01发布

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?

2条回答
趁早两清
2楼-- · 2019-04-17 00:22

With java.io, the relative path is dependent on the current working directory. With getResource you must have that resource in the classpath.

查看更多
倾城 Initia
3楼-- · 2019-04-17 00:30

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)

查看更多
登录 后发表回答