java - java中的绝对/相对路径(jar、ide)

标签 java path embedded-resource

我的程序使用Image.class,它可以帮助我接收图像。

Image img = new ImageIcon("Shooter2D/res/background.jpg").getImage();

当程序从开发环境运行时 - 一切正常,编译 jar 文件后 - 不起作用。 告诉我如何正确设置在 IDE (Intellij IDEA) 和存档中工作的路径。 Shooter2D.jar 包含:

- META-INF
Manifest-Version: 1.0
Main-Class: Shooter2Dv22082013.Main
- res
all pictures
- Shooter2Dv22082013
all .class files, main is Main.class

指示性数字:http://imageshack.us/photo/my-images/801/eyjv.png/

最佳答案

这就是 the javadoc关于ImageIcon的构造函数的说明:

Creates an ImageIcon from the specified file. The image will be preloaded by using MediaTracker to monitor the loading state of the image. The specified String can be a file name or a file path.

(强调我的)

您的图像未存储在文件中。它不在您的文件系统中。它位于类路径中的一个 jar 中。这就是您想要加载它的地方。无论应用程序的 jar 文件位于最终用户计算机上的何处,您的程序都希望从该 jar 文件加载它。并且此 jar 文件中的所有资源都可以从 ClassLoader 中获取。

所以你应该使用

new ImageIcon(MyClass.class.getResource("/res/background.jpg"))

new ImageIcon(MyClass.class.getClassLoader().getResource("res/background.jpg"))

关于java - java中的绝对/相对路径(jar、ide),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18379674/

相关文章:

c# - RazorEngine 字符串布局和部分?

java - 从 java.io.File 获取 java.nio.file.Path 对象

java - 在不同文件系统之间复制目录内容的干净方法?

c# - 在 WPF TextBox 中禁止特殊字符 ("\/: ? "< > |") 的可重用但简单有效的方法是什么?

java - 带有 MouseListener 的 CardLayout 不起作用

java - 在 jar 文件中包含一个文本文件并读取它

c# - 如何检查图像对象是否与资源中的对象相同?

java - 在 Intent 之间传递类 ArrayList

java - spring-boot-starter-parent 在 pom 文件中到底做了什么?

java - 用玩! GAE 上的缓存