在Java中使用相对路径打开资源 [英] open resource with relative path in Java

查看:30
本文介绍了在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 加载将加载我的资源(目录和文件)的资源加载器类.

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 which path to use for 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();

这篇关于在Java中使用相对路径打开资源的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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