如何访问位于项目文件夹外部和项目类路径外部的.properties文件?

时间:2015-02-16 09:15:24

标签: java java-ee properties inputstream java-ee-6

我在尝试检索位于项目根目录之外的 config.properties 文件时遇到以下问题。

所以我有这样的情况:

CONTAINER DIRECTORY
     |
     |
     |------> config.properties
     |
     |
     |------>PROJECT-ROOT
                 |
                 |
                 |
                 |------> src
                     |
                     |
                     |------> mainPkg (the package name)
                                 |
                                 |
                                 |------> Main (the main class containing the main() method)

通过位于类中的 main()方法,我必须访问同时位于同一位置的 config.properties 文件项目根文件夹的级别(并且不在项目类路径中)。

我必须使用相对路径所以我必须做这样的事情:从项目内的文件夹开始我必须回来直到 CONTAINER DIRECTORY 这里采用 config.properties 文件

我该怎么办? (我在Windows环境下)

1 个答案:

答案 0 :(得分:2)

我认为,在您的情况下,最好使用您的课程提供的Classloader

它应该像这样工作:

getClass().getClassLoader().getResources("config.properties");

唯一的问题是,您无法在像main这样的静态方法中编译该代码。 如果要以静态方法运行它,则应将其更改为:

Main.class.getClassLoader().getResources("config.properties");
相关问题