Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
885 views
in Technique[技术] by (71.8m points)

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();

enter image description here

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!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 (e.g. in Maven: /src/main/java, /src/main/resources).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...