英文:
How to load and parse (ant style) properties file in Java?
问题
如何在Java中将属性文件加载到Property对象中并解析属性值(`${x}`会像ant属性一样被替换)?例如使用以下属性文件:
foo=1
bar=${foo}.0
我需要将`bar`属性获取为`1.0`,而不是`${foo}.0`。有没有简单的方法来实现这个?
编辑:
Alex的解决方案适用于简单的情况。在我的情况下,我不得不解决另一个问题,导致了这个问题:[按顺序从Java属性文件中提取值?][1]。
加载和解析属性的示例代码如下:
```java
import java.util.*;
import java.io.*;
import org.apache.commons.text.StringSubstitutor;
public class Prop {
Properties parsedProperties = null;
public static Properties parseProperties(String filename) {
// 内部辅助类用于保持属性的顺序:
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();
// 测试 - 写入示例属性文件:
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(); }
// 读取并解析属性:
app.parsedProperties = parseProperties("config.properties");
// 调试打印:
for (Object k : app.parsedProperties.keySet()) {
System.out.println((String)k + " = " + app.parsedProperties.getProperty((String)k));
}
}
}
<details>
<summary>英文:</summary>
How to load property file into Property object in Java and get property values parsed (`${x}` gets replaced as it is done for ant properties)? For example using this property file:
foo=1
bar=${foo}.0
I need to get `bar` property as `1.0` instead `${foo}.0`. Is there a easy way for this?
EDIT:
Alex's solution works for simple scenarios. In my case I had to solve another issue leading to this question: [Pulling values from a Java Properties file in order?][1].
Resulting sample code for loading and parsing properties:
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));
}
}
}
[1]: https://stackoverflow.com/questions/1312383/pulling-values-from-a-java-properties-file-in-order
</details>
# 答案1
**得分**: 3
```java
// 导入必要的类和包
import org.apache.commons.text.StringSubstitutor;
// 初始化示例属性
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}
注意:上述内容是您提供的代码的翻译,可能会因为格式限制而略有不同。
英文:
You may use StringSubstitutor
from Apache Commons Text, its Maven dependency is pretty modest (~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>
Code example:
// 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;
}
Output:
resolved: {bar=5.5.0, foo=5.5, baz=5}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论