java的相对路径 [英] java relative path

查看:78
本文介绍了java的相对路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用下面的代码段会引发空指针异常,但我找不到原因:

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

我使用 getResources 错误吗?我什至尝试输入完整路径,例如"D:\ Workspace ...",双反斜杠,双正斜杠,但是我得到了空指针的例外.我唯一没有尝试过的方法是使用Java的路径分隔符,但由于它在Windows上运行,因此目前不应该成为问题.我想念什么?

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?

谢谢!

推荐答案

getResource

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).

/是资源的根目录.它等效于 src 文件夹中的根 ./i3d/resourcesloader/libraries/lib.txt 是访问资源的正确方法.

/ 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.

最好将资源分离到由构建工具合并的单独文件夹中(例如,在Maven中:/src/main/java /src/main/resources).

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).

这篇关于java的相对路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆