使用 URL 或文件(在 ImageIO.read 中) [英] Using URL or File (in ImageIO.read)
问题描述
我制作了一个使用多个图像的应用程序.我有两种方式来运行我的应用程序:
- 在idea中按run
- 制作一个胖 jar 文件并从控制台运行它 java -jar app.jar
如果我想从 Idea
运行它,我必须使用:
BufferedImage backgroundImage = ImageIO.read(new File("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/example/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屋!