我无法使用 getClassLoader 方法加载图像

I am not able load image using getClassLoader Method

下面是我正在尝试使用的代码。

 InputStream in = new BufferedInputStream(Tester.class.getClassLoader().getResourceAsStream("appResources/img/GESS.png"));
 Image image=null;  
 try {
         image = ImageIO.read(in);
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
 System.out.println(image);

'image' 在我打印的时候变成空值。

试试这个:

InputStream in = Tester.class.getResourceAsStream("your/path");
Image image=null;  
try {
    image = ImageIO.read(in);
} catch (IOException e) {
    e.printStackTrace();
}
System.out.println(image);

值或 your/pathappResources/img/GESS.png/appResources/img/GESS.png,具体取决于您的 Maven 配置和您为项目设置的目录。

例如,如果您将以下条目添加到 pom.xml 文件中:

<resources>
    <resource>
        <directory>src/main/appResources</directory>
    </resource>
</resources>

然后,您可以使用更短的路径获取相同的资源,因为您的程序知道在哪里寻找资源:

InputStream in = Tester.class.getResourceAsStream("img/GESS.png");
Image image=null;  
try {
    image = ImageIO.read(in);
} catch (IOException e) {
    e.printStackTrace();
}
System.out.println(image);

更多信息here and here

你可以使用 InputStream instream=Thread.currentThread().getContextClassLoader().getResourceAsStream("appResources/img/GESS.png");

你这样用 InputStream instream=Thread.currentThread().getContextClassLoader().getResourceAsStream("appResources/img/GESS.png");

这是我用于图像加载的两个实用方法。

public static Image getImage(final String pathAndFileName) {
    try {
        return Toolkit.getDefaultToolkit().getImage(getURL(pathAndFileName));
    } catch (final Exception e) {
        //logger.error(e);
        return null;
    }
}

public static URL getURL(final String pathAndFileName) {
    return Thread.currentThread().getContextClassLoader().getResource(pathAndFileName);
}