我有一个文本文件,其中包含以键=值方式格式化的信息。如何查找键并返回值。
例如,假设该文件具有:
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);
关于java - 返回文本文件中包含字符串的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10746832/