gpt4 book ai didi

java - 在jar包中定位资源

转载 作者:搜寻专家 更新时间:2023-11-01 01:47:52 24 4
gpt4 key购买 nike

我有一个静态类,在该类中图像被加载到 BufferedImage 对象中,如下所示:

File groundTopImageFile = new File("src/main/resources/ground - grass top.png");

现在,当我使用 Maven2 从中创建一个可执行 jar 时,一切正常,除了它找不到图像文件。我查看了jar,图片文件已经全部放在jar的根目录下了,所以我尝试使用:

File groundTopImageFile = new File("ground - grass top.png");

但没有成功。同样以这种方式,我不能再在 Eclipse 中使用相同的代码。有什么方法可以使它在 jar 和 Eclipse 中都起作用吗?

这是我的 Pom.xml 文件:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.WetWindmill</groupId>
<artifactId>Sheepness</artifactId>
<name>Sheepness</name>
<version>0.0.1-SNAPSHOT</version>
<description>Equilibrium reaction visualized with sheep :)</description>

<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.4</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.5.8</version>
</dependency>
</dependencies>

<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.6</source>
<target>1.6</target>
</configuration>
</plugin>

<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<executions>
<execution>
<id>unpack-dependencies</id>
<phase>generate-resources</phase>
<goals>
<goal>unpack-dependencies</goal>
</goals>
</execution>
</executions>
</plugin>

<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<configuration>
<archive>
<manifest>
<mainClass>controller.Sheepness</mainClass>
<packageName>com.WetWindmill.Sheepness</packageName>
</manifest>
<manifestEntries>
<mode>under development</mode>
<url>www.WetWindmill.com/Projects/Sheepness/</url>
</manifestEntries>
</archive>
</configuration>
</plugin>
</plugins>

<resources>
<resource>
<directory>${basedir}/target/dependency</directory>
</resource>
<resource>
<directory>${basedir}/src/main/resources</directory>
</resource>
</resources>
</build>
</project>

最佳答案

使用ImageIO.read(inputStream)并使用 ClassLoader.getResourceAsStream() 读取 InputStream

示例代码:

String resourceName = "my/picfolder/mypic.jpg";
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
InputStream stream = classLoader.getResourceAsStream(resourceName);
BufferedImage bi = ImageIO.read(stream);

注意:

在我的代码示例中,my/picfolder src/main/resources 的相对文件夹层次结构。

关于java - 在jar包中定位资源,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3915725/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com