gpt4 book ai didi

java - 如何在属性文件中定义对象数组并从 Java 程序中读取

转载 作者:太空宇宙 更新时间:2023-11-04 09:36:37 25 4
gpt4 key购买 nike

我有一个像这样的属性文件。

property[0].name=A
property[0].value=1
property[1].name=B
property[1].value=2
property[2].name=C
property[2].value=3

如何使用 ResourceBundle 或 Properties 在普通 java 程序中将此文件读取为类 {name, value} 的对象列表?

这是类(class)。

public class XYZ {
private String name;
private String value;
// Getters & Setters
}

我需要像这样。

ArrayList<XYZ> propertiesList = SomeUtility.getProperties("property", XYZ.class);

实用程序类可能是这样的。

public class SomeUtility {
public static ArrayList getProperties(String key, Class cls) {
//logic
}
}

最佳答案

我可能不太明白您想要什么,所以请随时纠正我并给我更多的限制,但这里有一个简单的方法来读取位于项目中某处的 Properties 文件:

private static void readPropertiesFile(String path) throws IOException {

java.util.Map<String, String> map = new java.util.LinkedHashMap<>();
Properties properties = new Properties();

InputStream inputStream = new FileInputStream(path);
properties.load(inputStream);

for (String name : properties.stringPropertyNames()) {
map.put(name, properties.getProperty(name));
}
for (java.util.Map.Entry<String, String> entry : map.entrySet()) {
System.out.printf("Property Key: %s, Property Value: %s%n", entry.getKey(), entry.getValue());
}
}

输出

Property Key: property[0].name, Property Value: A
Property Key: property[1].name, Property Value: B
Property Key: property[0].value, Property Value: 1
Property Key: property[1].value, Property Value: 2
Property Key: property[2].name, Property Value: C
Property Key: property[2].value, Property Value: 3

关于java - 如何在属性文件中定义对象数组并从 Java 程序中读取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56435094/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com