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

问题描述 投票:0回答:1

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

所以我有这样的情况:

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

从位于Main类内部的main()方法,我必须访问位于项目根文件夹的同一级别的config.properties文件(并且它在项目类路径之外)。

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

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

java java-ee properties inputstream java-ee-6
1个回答
2
投票

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

它应该像这样工作:

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

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

Main.class.getClassLoader().getResources("config.properties");
© www.soinside.com 2019 - 2024. All rights reserved.