【问题标题】:How to load and parse (ant style) properties file in Java?如何在 Java 中加载和解析(ant 风格)属性文件?
【发布时间】:2020-05-04 11:10:17
【问题描述】:

如何在 Java 中将属性文件加载到 Property 对象中并解析属性值(${x} 被替换为 ant 属性)?例如使用这个属性文件:

foo=1
bar=${foo}.0

我需要将bar 属性设为1.0 而不是${foo}.0。有什么简单的方法吗?

编辑: Alex 的解决方案适用于简单的场景。就我而言,我必须解决导致这个问题的另一个问题:Pulling values from a Java Properties file in order?

用于加载和解析属性的示例代码:

import java.util.*;
import java.io.*;
import org.apache.commons.text.StringSubstitutor;

public class Prop {

    Properties          parsedProperties   = null;

    public static Properties parseProperties(String filename) {
        // inner helper class keeping order of properties:
        class LinkedProperties extends Properties {

            private static final long serialVersionUID = 1L;
            private final HashSet<Object> keys = new LinkedHashSet<Object>();

            public LinkedProperties() {
            }

            public Iterable<Object> orderedKeys() {
                return Collections.list(keys());
            }

            public Enumeration<Object> keys() {
                return Collections.<Object>enumeration(keys);
            }

            public Object put(Object key, Object value) {
                keys.add(key);
                return super.put(key, value);
            }
        }

        LinkedProperties result = new LinkedProperties();
        try (InputStream input  = new FileInputStream(filename)) {

            result.load(input);

            @SuppressWarnings("unchecked")
            StringSubstitutor sub = new StringSubstitutor((Map) result);

            for (Object k : result.orderedKeys()) {
                result.setProperty((String)k, sub.replace(result.getProperty((String)k)));
            }
        } catch (IOException ex) { ex.printStackTrace(); }

        return ((Properties)result);
    }

    public static void main(String[] args) {
        Prop app = new Prop();

        // test - write sample properties file:
        try {
            PrintWriter writer = new PrintWriter(new FileWriter("config.properties"));
            writer.println("foo=1");
            writer.println("bar=1.${foo}");
            writer.println("baz=${bar}.0");
            writer.println("xxx=V.${baz}");
            writer.close();
        } catch (IOException ex) { ex.printStackTrace(); }

        // read and parse properties:
        app.parsedProperties = parseProperties("config.properties");

        // debug print:
        for (Object k : app.parsedProperties.keySet()) {
            System.out.println((String)k + " = " + app.parsedProperties.getProperty((String)k));
        }
    }
}

【问题讨论】:

  • Spring 有这个,但不确定在不拉动大量其他 Spring 功能依赖项的情况下获得它有多容易
  • 谢谢。 Ant 有这个,但是这里同样适用,如何避免从 ant Project 等中拉出一大堆依赖项?

标签: java properties ant


【解决方案1】:

您可以使用来自 Apache Commons Text 的 StringSubstitutor,它的 Maven 依赖项非常适中(~200K):

<!-- https://mvnrepository.com/artifact/org.apache.commons/commons-text -->
<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-text</artifactId>
    <version>1.8</version>
</dependency>

代码示例:

// init sample properties
Properties p = new Properties();
p.setProperty("foo", "${baz}.${baz}");
p.setProperty("bar", "${foo}.0");
p.setProperty("baz", "5");

Properties resolved = parseProperties(p);

System.out.println("resolved: " + resolved);
/////

public static Properties parseProperties(Properties orig) {
    Properties result = new Properties();
    StringSubstitutor sub = new StringSubstitutor((Map) orig);
    orig.entrySet().forEach(e -> result.put(e.getKey(), sub.replace(e.getValue())));
    return result;
}

输出:

resolved: {bar=5.5.0, foo=5.5, baz=5}

【讨论】:

  • 看起来很有希望。它可以用于相反的方式吗?我的意思是在加载属性文件期间?
  • 我不这么认为 - 您需要提供必须替换变量的输入字符串(.properties 文件的内容)和包含变量的映射(加载的属性实例) .解决变量后,您必须再次“重新加载”属性。
  • 我认为这会起作用: public static Properties parseProperties(Properties orig) { Properties result = new Properties(); StringSubstitutor sub = new StringSubstitutor((Map) orig); for (Map.Entry e : orig.entrySet()) { result.put(e.getKey(), sub.replace(e.getValue())); } 返回结果; } 然后简单地使用这个方法:Properties parsedProp = parseProperties(prop);
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-07-06
  • 2011-05-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-01-02
  • 1970-01-01
相关资源
最近更新 更多