简体   繁体   中英

Incorrect relative path in java

My issue is in the code here (seperated for debugging purposes):

// creating newUniversePane
Scene newUniverseScene = new Scene(newUniversePane, 300, 200);
Class<? extends WorldNoteOrganizerMainController> aClass = getClass();
URL resource = aClass.getResource("../../resources/css/main.css");
String s = resource.toExternalForm();
newUniverseScene.getStylesheets().add(s);
//more code

So, by looking at many examples here on Stack Overflow, it seems that my relative path is correct. However, when I run the program, and it reaches this code, it gives me an error.(I am attempted to add the css to a scene which will be added to a Stage as a popup)

Error message:

Caused by: java.lang.NullPointerException at controller.WorldNoteOrganizerMainController.handleNewUniverse(WorldNoteOrganizerMainController.java:169)

This error points to the line:

String s = resource.toExternalForm();

which is because resource is null. I have tried many different paths to try to get the file, but have not been successful. Also, I looked around on here, so that I am not repeating a question, but I could not find any questions that would help. I found relative class path questions, but they did not help me fix this. Any help would be greatly appreciated! I have added relative information to the end.

Actual one-liner code:

newUniverseScene.getStylesheets().add(getClass().getResource("/../../resources/css/main.css").toExternalForm();

Paths tried:

URL resource = aClass.getResource("/../resources/css/main.css");
URL resource = aClass.getResource("/resources/css/main.css");

Snapshot of hierarchy:

在此处输入图片说明

You need to find out what folder your app is at, when it runs, and how you look it up. Using this.getClass().getResource() the lookup is relative to the location of the class file itself, if the path begins with anything other than "/", When the path begins with "/", it is assumed to be an "absolute" path, and it will start at the "top" of the classpath (which in Eclipse ought to be the "target" folder). So - in you case, you would probably need to use "/css/main.css" (since src/main/resources/* will be copied to target/) - and as pointed out below, "relative paths" do not make sense here.

When you are using relative path, use this:

aClass.getClassLoader().getResource("relative-path");

If you are using Intellij there is an option that gives you the relative path by right clicking on the file.

当您在Inillj IDEA中将资源文件夹指定为资源文件夹(黄色小图标)时,然后调用getClass().getResources()Inillj IDEA您进入资源目录本身,因此只需使用getClass().getResources("css/main.css")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM