在jar包中定位资源

4

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

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

现在我使用Maven2创建可执行的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>
5个回答

7

使用 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 目录下的文件夹层次结构。


1
URL imgURL = getClass().getResource("/ground - grass top.png");
if (imgURL != null)
{
  return new ImageIcon(imgURL, "Ground Grass Top");
}
else
{
  logger.error("Couldn't find file: " + "ground - grass top.png");
  return null;
}

1
不要使用src/main/resources,它不会被打进jar包中。 - Sean Patrick Floyd
1
在Maven项目中,任何直接位于src/main/resources内的内容都将被复制到jar包的根目录。 - Sean Patrick Floyd
2
从问题中看来,图像位于JAR的根目录(默认包)。您当前的代码将从当前包加载它,而不是从根/默认包中加载。最好在图像名称前添加一个前导斜杠或使用getClass()。getClassloader()。getResource(String)加载资源而不带前导斜杠(类似于“seanizer”在其答案中提出的方式)。 - Neeme Praks

0

不要使用"/./resources/back_img.png",而要使用ClassLoader的"resources/back_img.png"。 这是一个例子:

    String path = "resources/back_img.png";
    ClassLoader cl = ImageHandler.class.getClassLoader();
    URL imgURL = cl.getResource(path);
    //URL imgURL = ImageHandler.class.getResource(path);

    if (imgURL != null) {
        ImageIcon icon = new ImageIcon(imgURL, description);
        Image img = icon.getImage();
        Image sizedImg = img.getScaledInstance(width, height, Image.SCALE_DEFAULT);
        return new ImageIcon(sizedImg);
    } else {
        System.err.println("Couldn't find file: " + path);
        return null;
    }

0
使用类装载器的getResourceAsStream()方法。

0
你解决了我的问题,Sean Patrick Floyd。虽然不同的IDE会有所不同,但是通过查看jar文件的结构,我们知道相对路径。 就像我的情况一样,我使用Netbeans,我的文件放在 src/my/picfolder/mypic.jpg (Sean是 src/main/resources/my/picfolder/mypic.jpg),但是当构建后,提取jar文件后,我们会看到图像在my/picfolder/mypic.jpg中。因此,当我们调用getResourceAsStream时,相对路径必须为my/picfolder/mypic.jpg

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接