我的项目结构如下所示。我不想将配置文件作为资源包含在内,而是在运行时读取它,这样我们就可以简单地更改设置而无需重新编译和部署。我的问题是两件事
- 尽管我尝试了各种方法,但读取文件仍然无法正常工作(请参阅下面我正在尝试的当前实现)
- 使用 gradle 时,我是否需要告诉它如何构建/或部署文件以及在哪里?我认为这可能是问题的一部分……在进行 gradle 构建或尝试在 Eclipse 中进行调试时,配置文件未部署。
我的项目结构:
myproj\
\src
\main
\config
\com\my_app1\
config.dev.properties
config.qa.properties
\java
\com\myapp1\
\model\
\service\
\util\
Config.java
\test
配置.java:
public Config(){
try {
String configPath = "/config.dev.properties"; //TODO: pass env in as parameter
System.out.println(configPath);
final File configFile = new File(configPath);
FileInputStream input = new FileInputStream(configFile);
Properties prop = new Properties()
prop.load(input);
String prop1 = prop.getProperty("PROP1");
System.out.println(prop1);
} catch (IOException ex) {
ex.printStackTrace();
}
}
最佳答案
答案 1。
reading the file just isn't working despite various ways i have tried (see current implementation below i am trying)
根据您描述的配置文件的位置,
改变
String configPath = "/config.dev.properties";
到
String configPath = "src\main\config\com\my_app1\config.dev.properties";
但是请先阅读第二个答案。
答案 2:
When using gradle, do i needto tell it how to build/or deploy the file and where? I think that may be part of the problem..that the config file is not getting deployed when doing a gradle build or trying to debug in Eclipse.
你有两个选择:
- 将您的
config
目录重命名为resources
。 Gradle 自动在“src/main/resources”目录下构建资源。 让 Gradle 知道要将其视为资源的附加目录。
sourceSets { main { resources { srcDirs = ["src\main\config\com\my_app1"] includes = ["**/*.properties"] } } }
关于Java/Gradle 读取外部配置文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42307865/