Java 图像已加载到 ide 但未构建 jar
Java images loaded in ide but not built jar
我的文件路径如下:
+------------+ +-----------------+ +------------------+
| | | | | |
| src +-----------> com +--+---> application |
| | | | | | |
+------------+ +-----------------+ | +------------------+
|
| +------------------+
| | |
+---> resources |
| |
+------------------+
我的代码在应用程序文件夹中,我要加载的图片在资源中。
我正在使用以下代码将图像从资源中获取到应用程序中的 class(图像是 BufferedImage)。
image = ImageIO.read(new File("./src/com/resources/Pad.png"));
这似乎在我的 IDE (intellij) 中有效,因为我可以看到加载的图像为 shown
但是,当我构建时,图像没有显示。我正在建设:
文件 -> 项目结构 -> 工件 -> Green plus -> JAR -> 来自具有依赖项的模块 -> 我的主要 class 位置 -> 提取到目标 Jar
然后我构建工件 -> 构建。
所以当我到达构建的 jar 的目的地并且 运行 它 none 的图片正在 shown
我通过提取确实包含图片的 jar 来检查图像是否在构建的 jar 中,但由于某种原因代码没有加载图片。
构建 jar 中的 src 路径不可用。您应该使用 class 加载程序从 class 路径加载资源。例如。 (假设 'src' 是 class 路径根)
image = ImageIO.read(new File(this.getClass()
.getResource("com/resources/Pad.png").getPath());
根据@MadProgrammer 建议编辑。
您可以尝试将资源用作流而不是文件。
image = ImageIO.read(this.getClass().getClassLoader().getResourceAsStream("com/resources/Pad.png"))
我的文件路径如下:
+------------+ +-----------------+ +------------------+
| | | | | |
| src +-----------> com +--+---> application |
| | | | | | |
+------------+ +-----------------+ | +------------------+
|
| +------------------+
| | |
+---> resources |
| |
+------------------+
我的代码在应用程序文件夹中,我要加载的图片在资源中。
我正在使用以下代码将图像从资源中获取到应用程序中的 class(图像是 BufferedImage)。
image = ImageIO.read(new File("./src/com/resources/Pad.png"));
这似乎在我的 IDE (intellij) 中有效,因为我可以看到加载的图像为 shown
但是,当我构建时,图像没有显示。我正在建设:
文件 -> 项目结构 -> 工件 -> Green plus -> JAR -> 来自具有依赖项的模块 -> 我的主要 class 位置 -> 提取到目标 Jar
然后我构建工件 -> 构建。
所以当我到达构建的 jar 的目的地并且 运行 它 none 的图片正在 shown
我通过提取确实包含图片的 jar 来检查图像是否在构建的 jar 中,但由于某种原因代码没有加载图片。
构建 jar 中的 src 路径不可用。您应该使用 class 加载程序从 class 路径加载资源。例如。 (假设 'src' 是 class 路径根)
image = ImageIO.read(new File(this.getClass()
.getResource("com/resources/Pad.png").getPath());
根据@MadProgrammer 建议编辑。
您可以尝试将资源用作流而不是文件。
image = ImageIO.read(this.getClass().getClassLoader().getResourceAsStream("com/resources/Pad.png"))