Why does Image.IO.read () return null in this case?

ImageLoader.java:

public class ImageLoader {
    private static BufferedImage image;

    public ImageLoader() {
    }

    public BufferedImage loadImage(String filePath) throws IOException {
        image = ImageIO.read(this.getClass().getResourceAsStream(filePath));
        return image;
    }

    public static BufferedImage loadImage(Class classPath, String filePath) throws IOException {
        image = ImageIO.read(classPath.getResourceAsStream(filePath));
        return image;
    }
}

Library.java:

public class Library {
    public static final String ResourcePath = "./res/";
    public static final String ImagePath = ResourcePath + "Images/";
}

Using ImageLoader.java in three ways:

  • BufferedImage test = new ImageLoader().loadImage(Library.ImagePath + "imageFile.png");

  • BufferedImage test = new ImageLoader().loadImage(Main.class, Library.ImagePath + "imageFile.png");

  • BufferedImage test = new ImageLoader().loadImage("/Images/" + "imageFile.png");

Why does the 3rd case work like this, but the first and second cases do not? I believe this has something to do with a static variable Library.ImagePath.

If there is a way to fix this, describe below!

+4
source share
1 answer

This seems to be related to your path to the image. When you expand a variable, this value

./res/Images

but from your third example, it looks like the image is on the class path in

/Images/imageFile.png

So try changing ImagePath to:

public static final String ImagePath = "/Images/";

(: ), , , "". , , "res" , .

, :

myProject
+--- res
|    +---Images
|    \---Texts
\--- src

myProject res , File:

new File("./res/Images/..."); //Relative to the working directory of the app!
classPath.getResourceAsStream("/Images/..."); //Root is your classpath, i.e. "res"!
+2

Source: https://habr.com/ru/post/1621437/


All Articles