Home > Net >  Netbeans (12x)/Mavan include and load embedded resources?
Netbeans (12x)/Mavan include and load embedded resources?

Time:09-26

Simple question, how to include and load embedded resources from a Maven based project when using Netbeans 12x

In a traditional/Ant based project, it's possible to simply place embedded resources within the Source Package and load it using Class#getResource, but for some reason, a Maven based project does not work the same way.

The following code works when using Ant, but fails when using Maven:

import java.io.IOException;
import javax.imageio.ImageIO;

public class Main {

    public static void main(String[] args) throws IOException {
        new Main();
    }

    public Main() throws IOException {
        ImageIO.read(getClass().getResource("/images/Background.jpg"));
    }

}

So, the, simple, question is, how to include embedded resources when using Maven with Netbeans 12x

CodePudding user response:

Maven has its own requirements with regards to where sources files and "other resources" are stored. Unlike Ant, you can't simply drop "resources" into the src/main/java directory, instead, you need to add them to the src/main/resources directory.

For some reason, however, Netbeans doesn't seem to create this directory for you (at least not for the base "application" template I was using).

In this case, you need to create it yourself. You can do this manual from the command line or file manager, but Netbeans will allow you to create as well.

Start by right clicking on the root node of the project and select "New/Folder"

ProjectFolder

From the dialog, name the folder resource and then tap the "Browse" button (next to "Parent Folder"

Options

Select the src/main directory

DestinationFinally

Tap finish and a new "node" should appear in the project called "Other Sources"

Finally

Now, I wish I could say it was easy to add resources to this directory, but I just end up copying and pasting files directly to the directory using a file manager.

Once you have the resource included (and they should show up under the "Other Sources" node), you can reference them from your code.

The important thing to remember though is, you don't need to include resources in the path, as the contents of the directory are copied into the resulting product, not the directory itself.

So, with a layout of:

Final layout

The following code will load the image without issues:

import java.io.IOException;
import javax.imageio.ImageIO;

public class Main {

    public static void main(String[] args) throws IOException {
        new Main();
    }

    public Main() throws IOException {
        ImageIO.read(getClass().getResource("/images/Background.png"));
    }

}
  • Related