Java中使用相对路径打开资源
在我的 Java 应用程序中,我需要获取一些文件和目录。
这是程序结构:
./main.java
./package1/guiclass.java
./package1/resources/resourcesloader.java
./package1/resources/repository/modules/ -> this is the dir I need to get
./package1/resources/repository/SSL-Key/cert.jks -> this is the file I need to get
guiclass
加载 resourcesloader 类,该类将加载我的资源(目录和文件)。
至于文件,我尝试
resourcesloader.class.getClass().getResource("repository/SSL-Key/cert.jks").toString()
获取真实路径,但这种方法行不通。
我不知道该目录使用哪个路径。
In my Java app I need to get some files and directories.
This is the program structure:
./main.java
./package1/guiclass.java
./package1/resources/resourcesloader.java
./package1/resources/repository/modules/ -> this is the dir I need to get
./package1/resources/repository/SSL-Key/cert.jks -> this is the file I need to get
guiclass
loads the resourcesloader class which will load my resources (directory and file).
As to the file, I tried
resourcesloader.class.getClass().getResource("repository/SSL-Key/cert.jks").toString()
in order to get the real path, but this way does not work.
I have no idea which path to use for the directory.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(13)
我在使用
getClass().getResource("filename.txt")
方法时遇到问题。阅读 Java 文档说明后,如果您的资源与您尝试访问资源的类不在同一包中,则必须为其提供以
'/'
开头的相对路径。 推荐的策略是将资源文件放在根目录的“resources”文件夹下。 因此,例如,如果您具有以下结构:那么您可以按照 maven 的建议添加资源文件夹:
此外,您可以在资源文件夹中添加子文件夹
,并说您的文件名为
myfile.txt
,这样您现在,愚蠢的路径问题就出现了。假设您的 com.mycompany.myapp 包中有一个类,并且您想要访问 myfile.txt 文件从您的资源文件夹中。 有人说你需要给出:
或者
这两者都是错误的。 运行
mvn cleancompile
后,文件和文件夹将复制到:文件夹中。 但资源文件夹不存在,只有资源文件夹中的文件夹。 所以你有:
所以给
getClass().getResource("")
方法的正确路径是:这里是:
这将不再返回 null,但会返回你的类。
让我感到奇怪的是,
“resources”
文件夹也没有被复制,而只是直接复制“resources”
文件夹中的子文件夹和文件。 对我来说,“resources”文件夹也可以在“myapp/target/classes”下找到,这似乎是合乎逻辑的I had problems with using the
getClass().getResource("filename.txt")
method.Upon reading the Java docs instructions, if your resource is not in the same package as the class you are trying to access the resource from, then you have to give it relative path starting with
'/'
. The recommended strategy is to put your resource files under a "resources" folder in the root directory. So for example if you have the structure:then you can add a resources folder as recommended by maven in:
furthermore you can add subfolders in the resources folder
and say that your file is called
myfile.txt
so you haveNow here is where the stupid path problem comes in. Say you have a class in your
com.mycompany.myapp package
, and you want to access themyfile.txt
file from your resource folder. Some say you need to give the:or
both of these are wrong. After I ran
mvn clean compile
, the files and folders are copied in the:folder. But the resources folder is not there, just the folders in the resources folder. So you have:
so the correct path to give to the
getClass().getResource("")
method is:here it is:
This will no longer return null, but will return your class.
It is strange to me, that the
"resources"
folder is not copied as well, but only the subfolders and files directly in the"resources"
folder. It would seem logical to me that the"resources"
folder would also be found under `"myapp/target/classes"提供相对于类加载器的路径,而不是您从中获取加载器的类。 例如:
Supply the path relative to the classloader, not the class you're getting the loader from. For instance:
为了给那些不像其他人那样快速掌握这一点的人提供更多信息,我想提供我的场景,因为它的设置略有不同。 我的项目使用以下目录结构进行设置(使用 Eclipse):
我在从 res 目录加载资源时遇到问题。 我希望所有资源与源代码分开(仅用于管理/组织目的)。 因此,我要做的就是将 res 目录添加到 build-path 中,然后通过以下方式访问资源:
注意: 资源字符串开头省略了
/
,因为我使用的是 ClassLoader.getResource(String) 而不是 Class.getResource(String)。In the hopes of providing additional information for those who don't pick this up as quickly as others, I'd like to provide my scenario as it has a slightly different setup. My project was setup with the following directory structure (using Eclipse):
I was having issues loading my resources from the res directory. I wanted all my resources separate from my source code (simply for managment/organization purposes). So, what I had to do was add the res directory to the build-path and then access the resource via:
NOTE: The
/
is omitted from the beginning of the resource string because I am using ClassLoader.getResource(String) instead of Class.getResource(String).当您在类上使用“getResource”时,将根据类所在的包解析相对路径。在类加载器上使用“getResource”时,将根据根文件夹解析相对路径。
如果您使用绝对路径,则两个“getResource”方法都将从根文件夹开始。
When you use 'getResource' on a Class, a relative path is resolved based on the package the Class is in. When you use 'getResource' on a ClassLoader, a relative path is resolved based on the root folder.
If you use an absolute path, both 'getResource' methods will start at the root folder.
@吉安卡洛:
您可以尝试调用系统属性 user.dir ,它将为您提供 java 项目的根目录,然后将此路径附加到您的相对路径,例如:
@GianCarlo:
You can try calling System property user.dir that will give you root of your java project and then do append this path to your relative path for example:
对于那些使用 eclipse + maven 的人。 假设您尝试访问
src/main/resources
中的文件images/pic.jpg
。 这样做是完全正确的,但可能会导致空指针异常。 似乎 Eclipse 无法立即将 maven 目录结构中的文件夹识别为源文件夹。 通过从项目的源文件夹列表中删除 src/main/resources 文件夹并将其放回(项目>属性>java构建路径>源>删除/添加文件夹),我能够解决这个问题。
For those using eclipse + maven. Say you try to access the file
images/pic.jpg
insrc/main/resources
. Doing it this way :is perfectly correct, but may result in a null pointer exception. Seems like eclipse doesn't recognize the folders in the maven directory structure as source folders right away. By removing and the
src/main/resources
folder from the project's source folders list and putting it back (project>properties>java build path> source>remove/add Folder), I was able to solve this.可以细分为:
这意味着您正在尝试使用引导类加载资源。
相反,您可能想要类似的内容:
如果只有 javac 警告在非静态上下文上调用静态方法...
Can be broken down to:
Which means you're trying to load the resource using a bootstrap class.
Instead you probably want something like:
If only javac warned about calling static methods on non-static contexts...
为了获取文件的真实路径,您可以尝试以下操作:
Resourceloader 在这里是类名。
“resources/repository/SSL-Key/cert.jks”是文件的相对路径。 如果您的 guiclass 位于 ./package1/java 中,其余文件夹结构仍保留,则由于定义相对路径的规则,您将采用“../resources/repository/SSL-Key/cert.jks”作为相对路径。
这样您就可以使用 BufferedReader 读取文件。 不要使用字符串来标识文件的路径,因为如果路径中包含空格或某些非英文字母的字符,则会出现问题并且无法找到该文件。
In Order to obtain real path to the file you can try this:
Resourceloader is classname here.
"resources/repository/SSL-Key/cert.jks" is relative path to the file. If you had your guiclass in ./package1/java with rest of folder structure remaining, you would take "../resources/repository/SSL-Key/cert.jks" as relative path because of rules defining relative path.
This way you can read your file with BufferedReader. DO NOT USE THE STRING to identify the path to the file, because if you have spaces or some characters from not english alphabet in your path, you will get problems and the file will not be found.
下面的工作有效吗?
是否有原因无法指定包括包的完整路径?
Doe the following work?
Is there a reason you can't specify the full path including the package?
按照上面提到的两个答案。 第一个
应该是同一个东西吗?
Going with the two answers as mentioned above. The first one
Should be one and same thing?
我对 @jonathan.cone 的一个衬垫做了一个小修改(通过添加
.getFile()
)以避免空指针异常,并设置数据目录的路径。 这对我有用:I made a small modification on @jonathan.cone's one liner ( by adding
.getFile()
) to avoid null pointer exception, and setting the path to data directory. Here's what worked for me :用这个:
Use this:
在所有操作系统上工作的稳定方法之一是获取
System.getProperty("user.dir")
One of the stable way to work across all OS would be toget
System.getProperty("user.dir")