Java/Gradle 读取外部配置文件

标签 java gradle

我的项目结构如下所示。我不想将配置文件作为资源包含在内,而是在运行时读取它,这样我们就可以简单地更改设置而无需重新编译和部署。我的问题是两件事

  1. 尽管我尝试了各种方法,但读取文件仍然无法正常工作(请参阅下面我正在尝试的当前实现)
  2. 使用 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.

你有两个选择:

  1. 将您的config 目录重命名为resources。 Gradle 自动在“src/main/resources”目录下构建资源。
  2. 让 Gradle 知道要将其视为资源的附加目录。

    sourceSets {
        main {
            resources {
                srcDirs = ["src\main\config\com\my_app1"]
                includes = ["**/*.properties"]
            }
        }
     }
    

关于Java/Gradle 读取外部配置文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42307865/

相关文章:

java - 如何获取指定按键的按下和释放事件?

android - 编译期间已经存在的程序类型

Gradle根据子项目属性配置任务

android - 无法执行 aapt(AbstractIndexedListIterator.next(AbstractIndexedListIterator.java :80) 处的 NoSuchElementException

android - 修复导入Android示例工程时Gradle不兼容问题

java - 使用已插入的一些字段打开 Android 的联系人 Activity

Java - 使用递归返回列表

android - 如何在Android Studio中下载库?

java - hashcode() 和compareTo() 有什么关系?

java - 在构造函数中初始化值之前检查条件