在java中打开具有相对路径的资源

在java中打开具有相对路径的资源

问题描述:

在我的Java应用程序中,我需要获取一些文件和目录。

In my Java app I need to get some files and directories.

这是程序结构:

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

guiclass loads the resourcesloader class which will load my resources (directory and file).

关于文件,我试过

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 how to do the directory.

提供相对于类加载器的路径,而不是你从中获取加载器的类。例如:

Supply the path relative to the classloader, not the class you're getting the loader from. For instance:

resourcesloader.class.getClassLoader().getResource("package1/resources/repository/SSL-Key/cert.jks").toString();