Java 返回文本文件中包含字符串的行

Java 返回文本文件中包含字符串的行,java,Java,我有一个文本文件,其中包含以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>();

我有一个文本文件,其中包含以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);
//假设“input”得到了文件的内容
Map m=新的HashMap();
//这可能更有效,但无论如何
//将所有类型的换行符规格化为“\n”
input=input.replaceAll(“\r\n”,“\n”);
input=input.replaceAll(“\r”,“\n”);
//填充地图
字符串[]行=input.split(“\n”);
对于(int i=0;i
一大堆方法。你可以

a。逐行读取文件一次,拆分输入,然后填充映射

b。将正则表达式搜索作为一个整体应用于文件

c。你可以索引全文搜索这个东西


这完全取决于您的用例。很难推荐一种不理解上下文的方法。

< P>如果您只需要读取名称-值对,如果是配置性质的话,那么可以考虑使用java中的属性文件。
您可以查看这篇文章

在这里发布之前您尝试过什么吗?查看Java的属性文件。看起来你的键值文件和它们很相似。
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);