在文件java中搜索一个句子

时间:2015-06-13 06:22:07

标签: java file search

我真的很沮丧。 我有一个输入文件说input.txt。 input.txt的内容是

  Using a musical analogy, hardware is like a musical instrument and software is like the notes played on that instrument.

现在我想搜索文本

 like a musical instrument

如何在java中的input.txt中搜索上述内容。任何帮助???

2 个答案:

答案 0 :(得分:4)

为了在java中搜索模式,java在String中提供了contains()方法。尝试使用它,以下是用于此目的的代码片段,

public static void main(String[] args) throws IOException {
    FileReader reader = new FileReader(new File("sat.txt"));
    BufferedReader br = new BufferedReader(reader);
    String s = null;
    while((s = br.readLine()) != null) {
        if(s.contains("like a musical instrument")) {
            System.out.println("String found");
            return;
        }
    }
    System.out.println("String not found");
}

答案 1 :(得分:2)

您始终可以使用 String#contains()方法来搜索子字符串。在这里,我们将逐个读取文件中的每一行,并检查字符串匹配。如果找到匹配项,我们将停止阅读该文件并打印找到匹配项

package com.adi.search.string;

import java.io.*;
import java.util.*;

public class SearchString {

    public static void main(String[] args) {

        String inputFileName = "input.txt";
        String matchString = "like a musical instrument";
        boolean matchFound = false;

        try(Scanner scanner = new Scanner(new FileInputStream(inputFileName))) {

            while(scanner.hasNextLine()) {
                if(scanner.nextLine().contains(matchString)) {
                    matchFound = true;
                    break;
                }
            }
        } catch(IOException exception) {

            exception.printStackTrace();
        }

        if(matchFound)
            System.out.println("Match is found!");
        else
            System.out.println("Match not found!");
    }
}