我真的被这个困住了。我有一个输入文件说输入.txt。输入的内容.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 的输入.txt中搜索上述内容。有什么帮助吗???
为了在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");
}
您始终可以使用 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!");
}
}