'My resource does not load - "Input stream must not be null"

I read ~4 Stackoverflow Posts (1, 2) already, and did everything like it was explained there, but I get a NullPointerException while I try to load an Image.

Exception in thread "JavaFX Application Thread" java.lang.NullPointerException: Input stream must not be null

My package structure:

packages

Code where I try to load the image:

Image image = new Image(this.getClass().getResourceAsStream("/regexgolf2/ui/img/edit.png"));

I don't understand why It does not work.



Solution 1:[1]

Your images are in a package under the src folder. The class loader does not look there for files. The class loader looks for files in your class path.

In order for getResource to work in your case, you need to put the images in the class path.

I suggest you copy the image files manually to your build folder (under the same path, e.g. out/regexgolf2/ui/images and run your app again.

If it works you can start thinking of ways to get the files to the class path (e.g. copy them as part of the build/packaging process or putting them in another folder which is in the class path).

Solution 2:[2]

In the case of a netbeans maven javaFX project, the resource (img folder) must be in the resources folder:

enter image description here

Then you can load the resource, for example:

Image escribir = new Image(getClass().getResourceAsStream("/img/login.png"));

Solution 3:[3]

I have similar problem in IntelliJ, all look fine but didn't work. In my case, When I rebuild project, all work correct.

Solution 4:[4]

I had the same problem in IntelliJ , I wanted to show Image in ImageView on button click and this was a solution for me, don't use getClass().getResourceAsStream("imagePath");

Image image = new Image(String.valueOf(new File("/images/image3.png")));

Solution 5:[5]

You can try:

URL url = ClassLoader.getSystemClassLoader().getResource("img/pic.jpg");
Image imProfile = new Image(url.openStream());
ImageView profileImage = new ImageView(imProfile);

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 daramasala
Solution 2 zx485
Solution 3 Michael Piefel
Solution 4 Michu93
Solution 5 BabaNew