使用URL或文件(在ImageIO.read中) [英] Using URL or File (in ImageIO.read)
问题描述
- 在$ idea中按
run
- 制作一个胖的jar文件,从控制台运行
java -jar app.jar
如果我想从 Idea
我必须使用:
$ b BufferedImage backgroundImage = ImageIO.read新文件(res / field.png));
而不是
BufferedImage backgroundImage = ImageIO.read(getClass()。getClassLoader()。getResource(res / field.png));
< - 这就是我在jar文件中使用的情况
为什么?我以为他们差不多有没有什么普遍的办法,我的情况?
我总是使用:
BufferedImage backgroundImage = ImageIO.read(getClass()。getResource(res / field.png));
可以在IDE和jar中使用。 .getResource(...)返回一个URL,无论是jar://还是file://
请注意,路径或者以/如果你的类是com.example.Test,那么 / res /
指的是文件夹com /例如/ Test / res /.
甚至可以使用静态版本 - YourClassName.class.getResource(...),它允许您轻松地访问其他分支你的包树(你可以使用引用来自位于不同分支的类)
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)
这篇关于使用URL或文件(在ImageIO.read中)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!