简体   繁体   中英

java relative path

Using the snippet below throws me a null pointer exception, but i can't find the reason:

String path = ResourcesLoader.class.getResource("src/i3d/resourcesloader/libraries/lib.txt").toString();

在此处输入图片说明

Am i using the getResources wrong? I even tried to enter the full path, like "D:\\Workspace...", double backslashes, double forwardslashes but i get the exception of null pointer. The only thing i haven't tried is using java's path separator, but that shouldn't be a problem at this moment as it runs on Windows. What do i miss?

Thanks!

getResource searches via the classloader , so typically and simplified in the classpath. The src folder is not in the classpath – it only exists for the build. Depending on your build system (ANT, Maven, IDE internal) a resources folder may be merged into the classpath. You put your resource directly into the source folder which will also work (if the build process copies all non-Java resources to the class output folder or if the source folder is used for the output of the generated classes).

/ is the root for your resources if you use absolute resource locations. It is equivalent to the root within the src folder. /i3d/resourcesloader/libraries/lib.txt would be the correct way to access the resource.

It would be nicer to separate the resources in a separate folder that is merged by the build tool (eg in Maven: /src/main/java , /src/main/resources ).

It seems you are using NetBeans?

Just create a folder called src\\resources , get your files inside there, and call this.getClass().getResource("lib.txt"); .

Netbeans will pack that properly when building and the resources will be in the main folder inside the jar, so you can get without having to specify their folder.

您应该只提供从类加载点开始的相对路径(即,不带src ):

String path = ResourcesLoader.class.getResource("/i3d/resourcesloader/libraries/lib.txt").toString();

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