获取给定字符串的值

时间:2016-06-22 11:58:18

标签: java

我想搜索一个字符串并在文件中获取该字符串的值。 例如,文件包含类似这样的内容

  

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

3 个答案:

答案 0 :(得分:0)

您可以拆分并获取值。

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

并将包含值。

答案 1 :(得分:0)

您可以通过以下几种方式实现:

方式1:

逐行读取文件并将每一行拆分为=,并使用左侧部分作为键,右侧部分作为值。把它们放在HashMap中。在进行查找时,根据密钥从HashMap中读取它。

方式2:

在您当前的方法中,将每一行拆分为=,并将输入的键与左侧部分匹配,如果它与右侧部分匹配。

希望这有帮助。

答案 2 :(得分: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"));
相关问题