如何在Java中加载和解析(蚂蚁风格)属性文件?

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

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

foo=1
bar=${foo}.0

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

用于加载属性的最小独立工作示例(此处未进行解析/替换):

import java.util.*;
import java.io.*;

public class Prop {
     // convenience method: create sample properties file 
     public static void saveProps() {
        Properties prop = new Properties();
        try(OutputStream outputStream = new FileOutputStream("test.properties")){  
            prop.setProperty("foo", "1");
            prop.setProperty("bar", "${foo}.0");
            prop.store(outputStream, null);
        } catch (IOException e) { e.printStackTrace(); } 
     }

     // HERE I NEED TO LOAD AND PARSE PROPERTIES:
     public static void loadProps() {
        Properties prop = new Properties();
        try {
            InputStream in = new FileInputStream("test.properties");

            // NO parsing/replacement done here:
            prop.load(in);

            System.out.println("bar = " + prop.getProperty("bar"));
        } catch (IOException ex) { System.out.println(ex); }
     }
     public static void main(String []args){
        saveProps();
        loadProps();
     }
}
java properties ant
1个回答
2
投票

您可以使用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");

// print to string
StringWriter writer = new StringWriter();
p.list(new PrintWriter(writer));
String nonresolved = writer.toString();

String resolvedVars = StringSubstitutor.replace(nonresolved, p);
System.out.println("resolved: " + resolvedVars);

输出:

resolved:
-- listing properties --
bar=5.5.0
foo=5.5
baz=5
© www.soinside.com 2019 - 2024. All rights reserved.