我想搜索一个字符串并在文件中获取该字符串的值。 例如文件包含这样的内容
test=1
test2=2
如果给出搜索字符串 str="test2"那么它应该返回值 2 。 我尝试过的示例代码是
public class ScannerExample {
public static void main(String args[]) throws FileNotFoundException {
//creating File instance to reference text file in Java
String filePath = "c:/temp/test.txt";
//Creating Scanner instnace to read File in Java
String str = "text";
//Reading each line of file using Scanner class
BufferedReader br = new BufferedReader(new FileReader(filePath));
String sCurrentLine;
while ((sCurrentLine = br.readLine()) != null) {
if(sCurrentLine.contains(str)) {
result=true;
System.out.println("Found entry ");
break;
}
}
}
}
这里我检查值是否存在。请建议一些方法来获取它的值
sample.txt:
test=1
test2=2
testnew=new
testold=old2
最佳答案
只需使用 Properties
对象并用它加载文件
Properties p = new Properties();
try (Reader reader = new FileReader(filePath)) {
// Load the file
p.load(reader);
}
// Print the value of the parameter test2
System.out.println(p.getProperty("test2"));
关于java - 获取给定字符串的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37967379/