javapathgetresourcejavafx-webengine

How to give the correct path of a file in getClass().getResource()


In this fourm are a lot of questions but none is similar to mine.

I always get a NullPointerException if i try to jump two folders up in the directory. If i just jump up one folder, the program finds my .html file...

This is the java part where I load my html File. This Java file is in the package src and there in the package application.

@FXML
private void initialize() {
    webEngine = webView.getEngine();
    try {
        webEngine.load(getClass().getResource("../../local/offer/test.html").toExternalForm());
    }catch (Exception e) {
        e.printStackTrace();
    }
}


- src
   -application
       .java
-bin
-local
   -offer
       test.html

This is my folder structure. My .java is in the folder application. If i use ../ i go one folder up, so i search on the level of the application folder. No i use ../ again to go one folder up again, to search on thje src folder level. In my opinion no i can use local/offer/test.html.

So ../../local/offer/test.html should work in my opinion, but it doesn't

enter image description here


Solution

  • When using "../" means that you search at the previous folder so with "../test.html" you exit from the application folder and search for a file named test.html on the folder you show in the second picture.

    With the "../../test.html" you search two folders behind the application

    Also the getClass().getResource() searches on the project's folder instead of the classes