我有一個文本文件,其中包含以key = value方式格式化的信息。我如何查找關鍵字並返回值。在包含字符串的文本文件中返回一行
例如,假設該文件有:
KeyOne=ValueOne
KeyTwo=ValueTwo
,我想有這需要KeyOne並返回ValueOne的方法。
我有一個文本文件,其中包含以key = value方式格式化的信息。我如何查找關鍵字並返回值。在包含字符串的文本文件中返回一行
例如,假設該文件有:
KeyOne=ValueOne
KeyTwo=ValueTwo
,我想有這需要KeyOne並返回ValueOne的方法。
好了,我的心情很好:),未經測試:
//given that 'input' got the contents of the file
Map<String,String> m = new HashMap<String,String>();
//this can be done more efficient probably but anyway
//normalize all types of line breaks to '\n'
input = input.replaceAll("\r\n","\n");
input = input.replaceAll("\r","\n");
//populate map
String[] lines = input.split("\n");
for(int i=0 ; i< lines.length; i++){
String[] nv = lines[i].split("=");
m.put(nv[0],nv[1]);
}
//get value given key:
String key = "somekey";
String someValue = m.get(key);
System.out.println(someValue);
Scanner s = new Scanner("Filename");
Map<String, String> m = new HashMap<String, String>();
while(s.hasNext()){
String line[] = s.nextLine().split("=");
m.put(line[0], line[1]);
}
來獲取值:方式
m.get(ValueOne);
一大堆。你可以
a。 b。逐行讀取文件,分割輸入,然後填入地圖
b。對整個文件應用正則表達式搜索
c。你可以索引一個全文搜索的東西
這一切都取決於你的用例。很難推薦一種不理解背景的方法。
如果您只需要讀取名稱/值對,並且如果這是配置屬性,那麼您可以考慮在Java中使用屬性文件。
你可以看看這個http://www.mkyong.com/java/java-properties-file-examples/
你有沒有嘗試過之前發佈在這裏? – Blender
注意Java的屬性文件。看起來你的鍵值文件與它們相似。 http://docs.oracle.com/javase/6/docs/api/java/util/Properties.html –