我正在尝试从属性文件中提取数据并将其放入地图中。更准确地说:我有一个Properties
对象,其中文件包含以下内容:
something = Blah
somethingElse = BlahBlah
andAgain = BlahBlahBlah
# Parameters
param1 = One
param2 = Two
param3 = Three
# and so on...
param9 = Nine
我现在尝试使用键param...
提取属性的键和值,并将它们放在TreeMap
中。排序应与属性文件(param1
,... param9
)保持一致。到目前为止,这是我的代码:
/*
* First extract the properties which are stored in external file
*/
Properties props = extractProperties();
Map<String, String> sortedMap = new TreeMap<String, String>();
HashMap<String, String> map = new HashMap<String, String>();
if (checkPropertiesAvailable()) {
Enumeration e = props.propertyNames();
// iterate over properties
while (e.hasMoreElements()) {
String key = (String) e.nextElement();
// put key/value in HashMap
map.put(key, props.getProperty(key));
if (key.contains("param")) {
//
sortedMap.put(key, props.getProperty(key));
}
}
for (Map.Entry<String, String> entry : sortedMap.entrySet()) {
system.out.println("Value: " + entry.getValue());
}
}
不幸的是,参数(param1
,... param9
)未正确排序,我无法弄清楚它们目前是如何排序的。出了什么问题,我该如何对地图进行排序?
我很感激任何帮助!
答案 0 :(得分:0)
您的代码以排序方式打印属性。请检查此代码:
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Enumeration;
import java.util.Map;
import java.util.Properties;
import java.util.TreeMap;
public class TreeMapExample {
public static void main(String[] args) {
Properties props = new Properties();
try (FileInputStream input = new FileInputStream("src/main/resources/example.properties")) {
props = new Properties();
props.load(input);
} catch (IOException e) {
System.out.println("Failed to load properties from file.");
}
Map<String, String> sortedMap = new TreeMap<>();
Enumeration e = props.propertyNames();
while (e.hasMoreElements()) {
String key = (String) e.nextElement();
if (key.contains("param")) {
sortedMap.put(key, props.getProperty(key));
}
}
for (Map.Entry<String, String> entry : sortedMap.entrySet()) {
System.out.printf("[Key, Value]: %s, %s \n", entry.getKey(), entry.getValue());
}
System.out.println();
for (String s : sortedMap.keySet()) {
System.out.printf("[Key, Value]: %s, %s \n", s, sortedMap.get(s));
}
System.out.println();
for (String s : sortedMap.values()) {
System.out.printf("Value: %s \n", s);
}
}
}
输出是: {代码}
[Key, Value]: param1, One
[Key, Value]: param2, Two
[Key, Value]: param3, Three
[Key, Value]: param9, Nine
[Key, Value]: param1, One
[Key, Value]: param2, Two
[Key, Value]: param3, Three
[Key, Value]: param9, Nine
Value: One
Value: Two
Value: Three
Value: Nine