Ari
Ari

Reputation: 4999

JavaFX - Cannot Load Image Inside Project Directory

I am using netbeans. I have a project directory like this:

HTMLEdit/
        src/
           htmledit/
                   - pic.png
                   - MyClass.java

I tried to get the image, but it return null. I had trying both of these but still cannot get it to work:

System.out.println(getClass().getResourceAsStream("/pic.png"));

and

System.out.println(getClass().getResourceAsStream("pic.png"));

What's causing this weird behavior?

EDIT :

It looks like it's because I choosed JAVAFX Project when created the project. I recreate the project by choosing Java Project and it works fine. May be this is Netbeans bug.

Upvotes: 1

Views: 465

Answers (2)

lambad
lambad

Reputation: 1066

When you do getClass().getResourceAsStream("/pic.png")then the url that will be looked to access the file will be an absolute url. The absolute URL is indicated by the slash which is at the front of the resource location.

If you do getClass().getResourceAsStream("pic.png"), then a resource relative to the package where the class resides will be used.

Because you said that both of the getResourceAsStream() statements did not work in Netbeans, I checked the below JavaFX code in Netbeans and it worked perfectly.

public class MyClass extends Application{
    @Override
    public void start(Stage primaryStage) {
      Pane root = new Pane();
        Image images = new Image(getClass().getResourceAsStream("pic.png"));
        ImageView image = new javafx.scene.image.ImageView(images);
        root.getChildren().add(image);
        Scene scene = new Scene(root);
        primaryStage.setScene(scene);
        primaryStage.show();

    }



    public static void main(String[] args) {
        launch(args);
    }

}

Here is the structure and the output of the program. enter image description here

In case if you want to know the Netbeans version, I am using then it is Netbeans 8.0.2. Also, read the following post.

Different ways of loading a file as an InputStream

Upvotes: 1

Santiago Benoit
Santiago Benoit

Reputation: 994

getClass().getResourceAsStream() is used for files embedded inside your java jar file. You should use FileInputStream if you need to read a file from your file system as a stream of bytes. Here's the documentation: https://docs.oracle.com/javase/8/docs/api/java/io/FileInputStream.html

Upvotes: 1

Related Questions