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

12,739

Solution 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

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"));
Share:
12,739

Related videos on Youtube

quantumbyte
Author by

quantumbyte

Updated on July 08, 2022

Comments

  • quantumbyte
    quantumbyte almost 2 years

    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.

    • BitNinja
      BitNinja almost 10 years
      Is image a java.awt.Image?
  • quantumbyte
    quantumbyte almost 10 years
    Thanks! This fixed the problem and some other similar problems I had with images not loading from fxml files. How can I put them in a folder that is in the classpath / copy them as part of the build process? (I believe I should use something like Ant or Maven, would that fix it?)
  • daramasala
    daramasala almost 10 years
    yes, you can copy/package them using Ant or Maven. If you're using an IDE to build your app, then the IDE probably has some configuration to copy files during build. The general practice is to keep a separate folder for resources that are not source files. After you play around with these concepts you try googling for 'java standard directory structure'.
  • quantumbyte
    quantumbyte almost 10 years
    I will definitely look into that, I thought the location I put them is fairly common, but what would you recommend? Something like res/images/edit.png?
  • daramasala
    daramasala almost 10 years
    This is fine. You can leave the more advanced stuff (maven, standard dir structure) for when you want to package/distribute your app.