【问题标题】:How to load external properties file with Java without rebuilding the Jar?如何在不重建 Jar 的情况下使用 Java 加载外部属性文件?
【发布时间】:2017-03-29 04:49:50
【问题描述】:

我使用 gradle,它以 maven 风格构建项目,所以我有以下内容

src/main/java/Hello.javasrc/main/resources/test.properties

我的Hello.java 看起来像这样

public class Hello {
    public static void main(String[] args) {
        Properties configProperties = new Properties();
        ClassLoader classLoader =  Hello.class.getClassLoader();
        try {
            configProperties.load(classLoader.getResourceAsStream("test.properties"));
            System.out.println(configProperties.getProperty("first") + " " + configProperties.getProperty("last"));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

这很好用。但是我希望能够在我的项目之外指向.properties 文件,并且我希望它足够灵活,以便我可以指向任何位置无需每次都重建 jar。有没有办法不使用 File API 并将文件路径作为参数传递给 main 方法?

【问题讨论】:

    标签: java maven gradle


    【解决方案1】:

    你可以试试这个,它首先会尝试从项目主目录加载属性文件,这样你就不必重新构建 jar,如果找不到则从类路径加载

    public class Hello {
    
        public static void main(String[] args) {
            String configPath = "test.properties";
    
            if (args.length > 0) {
                configPath = args[0];
            } else if (System.getenv("CONFIG_TEST") != null) {
                configPath = System.getenv("CONFIG_TEST");
            }
    
            File file = new File(configPath);
            try (InputStream input = file.exists() ? new FileInputStream(file) : Hello.class.getClassLoader().getResourceAsStream(configPath)) {
                Properties configProperties = new Properties();
                configProperties.load(input);
                System.out.println(configProperties.getProperty("first") + " " + configProperties.getProperty("last"));
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }
    

    您可以将属性文件路径作为参数发送或将路径设置为环境变量名称CONFIG_TEST

    【讨论】:

    • 这不会让我灵活地在任何我想要的地方指定 .properties 文件(我在我的问题中提到过。)我还提到我正在寻找一个不使用文件 API 和传递文件的解决方案路径作为主方法的参数
    • @user1870400 添加路径作为参数
    • 感谢您的努力。再次正如我在问题中提到的那样,我正在寻找“不”使用 File API 并将文件路径作为参数传递给 main 方法的解决方案。
    • 哦,对不起。你可以设置一个包含路径的环境变量,从程序中读取环境变量来获取路径
    • @user1870400 如果你不传递路径也不使用文件API,你想象会发生怎样的奇迹?
    【解决方案2】:

    Archaius 对于这样一个简单的问题可能完全是矫枉过正,但它是管理外部属性的好方法。它是一个用于处理配置的库:配置层次结构、来自属性文件的配置、来自数据库的配置、来自用户定义源的配置。它可能看起来很复杂,但您永远不必担心再次手动滚动一个半损坏的解决方案来配置。入门页面有一个关于 using a local file as the configuration source 的部分。

    【讨论】:

    • 不知道是不是很简单。我试图在不使用外部库的情况下寻找解决方案,但我没有遇到任何问题。所以如果它很简单,你能告诉我如何在没有外部库的情况下做到这一点吗?一旦我的项目变得更加成熟,我肯定会考虑 Archaius。
    猜你喜欢
    • 2014-12-30
    • 1970-01-01
    • 2016-04-10
    • 2011-04-04
    • 1970-01-01
    • 2020-12-28
    • 2019-11-02
    • 1970-01-01
    • 2015-09-02
    相关资源
    最近更新 更多