2016-06-22 43 views
1

我想要搜索字符串并获取文件中该字符串的值。 例如文件中包含这样的获取给定字符串的值

测试= 1

测试2 = 2

如果搜索字符串str = “测试2” 中给出,那么它应该返回值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 
+0

HashMaps这样的文件?是的.. – Hackerdarshi

+0

你的代码不能编译。 –

+0

你可以添加关于test.txt的信息或发布它吗?每对(如test2 = 2)是否在单独的行中列出? – c0der

回答

0

只需使用一个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")); 
0

您可以分割,并获得价值。

String[] splits = sCurrentLine.split("="); 
System.out.println("Value is " + splits[1]) 

并将包含该值。

0

你可以做到在几个方面:

方法1:

逐行读取文件中的行,并通过=分割每一行,并使用左侧的键和右侧的部分价值。把它们放在HashMap。在查找的同时,根据密钥从HashMap中读取它。

方式2:

在你现在的做法,由=分割每行和匹配进入与左边的关键,如果它匹配返回的权利的一部分。

希望这会有所帮助。

+0

我没有改变它的方式。它已经写在两个单独的行上。我只是格式化它。你应该在评论之前查看问题历史。 – Sanjeev