【问题标题】:Searching for a sentence in a file java [closed]在文件java中搜索句子[关闭]
【发布时间】:2015-06-13 06:22:06
【问题描述】:

我真的很坚持这一点。 我有一个输入文件说 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中搜索上述内容。有什么帮助???

【问题讨论】:

  • 纯代码编写请求在 Stack Overflow 上是题外话——我们希望这里的问题与特定编程问题有关——但我们很乐意帮助您自己编写!告诉我们what you've tried,以及您遇到的问题。这也将有助于我们更好地回答您的问题。
  • 先生实际上我真的不知道我想用什么来在java中搜索这种内容。
  • 在寻求帮助之前,您真的应该努力自己解决问题。

标签: java file search


【解决方案1】:

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

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");
}

【讨论】:

    【解决方案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!");
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-06-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多