Using URL or File (in ImageIO.read)

。_饼干妹妹 提交于 2019-12-06 16:14:49

问题


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?


回答1:


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)




回答2:


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



来源:https://stackoverflow.com/questions/13231027/using-url-or-file-in-imageio-read

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!