Java 当文件中存在重复的键值对时,如何读取属性文件?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20511865/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to read the property file when duplicate key-value pair exist in the file?
提问by user3089783
I am loading my property file using the load()
of properties class.I am able to read the key-value pair of the property class using set,hashmap,treeset,enumeration, but it does not retrieve the duplicate pairs. The duplicate pairs are retrieved only once.
我正在使用load()
属性类加载我的属性文件。我能够使用 set、hashmap、treeset、enumeration 读取属性类的键值对,但它不会检索重复的对。重复对仅检索一次。
回答by Nishant Lakhara
Properties file sets key value pairs. All keys are unique so it will not catch duplicate pairs. Instead it will fetch the latest mapped pair. For example :
属性文件设置键值对。所有键都是唯一的,因此它不会捕获重复的对。相反,它将获取最新的映射对。例如 :
Sample file:
示例文件:
a=1
b=2
c=3
d=4
a=10
c=7
The properties class will return latest pairs i.e
属性类将返回最新的对,即
a=10
b=2
c=7
d=4
Still if your requirement is to find all the pairs whether duplicate or not , Use the following code that uses Scanner class and two arraylist objects.
如果您的要求是查找所有对是否重复,请使用以下使用 Scanner 类和两个 arraylist 对象的代码。
ArrayList k = new ArrayList();
ArrayList v = new ArrayList();
Scanner scan = new Scanner(new File("E:\abc.properties"));
while(scan.hasNextLine()) {
//System.out.println(scan.nextLine());
String split[] = scan.nextLine().trim().split("=");
if(split.length == 2) {
k.add(split[0]);
v.add(split[1]);
System.out.println("pair " + split[0] + ":" + split[1]);
}
//System.out.println("a");*/
}
回答by Mark
PropertiesConfigurationfrom Apache Commons Configuration supports loading a properties file with multiple entries with the same key.
来自 Apache Commons Configuration 的PropertiesConfiguration支持加载具有相同键的多个条目的属性文件。
Use the getStringArray(key) method or getList(key) method to access all values for the specified key.
使用 getStringArray(key) 方法或 getList(key) 方法访问指定键的所有值。
回答by Zak FST
you can use buffer reader to read lines of your file and split the result:
您可以使用缓冲区读取器读取文件的行并拆分结果:
public static void main(String[] args) throws IOException {
Reader file = new FileReader("C:/file.cfg");
BufferedReader br = new BufferedReader(file);
String line = br.readLine();
while (line != null) {
String obj[] = line.split("=");
for (int i=0 ; i<obj.length; i=+2 ){
System.out.println(obj[i]+"="+obj[i+1]);
line = br.readLine();
}
}
}