2 回答
TA贡献1934条经验 获得超2个赞
您已经在读取文件的每一行,因此使用该方法将是您的最佳解决方案String.contains()
if (x.contains(word) ...
如果给定的包含您传递给它的字符序列(或字符串),则该方法只是返回。contains()trueString
注意:此检查区分大小写,因此,如果要检查该单词是否存在任何大小写组合,只需先将字符串转换为相同的大小写:
if (x.toLowerCase().contains(word.toLowerCase())) ...
所以现在这里有一个完整的例子:
public static void main(String[] args) throws FileNotFoundException {
String word = args[0];
Scanner input = new Scanner(new File(args[1]));
// Let's loop through each line of the file
while (input.hasNext()) {
String line = input.nextLine();
// Now, check if this line contains our keyword. If it does, print the line
if (line.contains(word)) {
System.out.println(line);
}
}
}
TA贡献1851条经验 获得超4个赞
首先,您必须打开文件,然后逐行读取它,并检查该单词是否在该行中。
class Find {
public static void main (String [] args) throws FileNotFoundException {
String word = args[0]; // the word you want to find
try (BufferedReader br = new BufferedReader(new FileReader("foobar.txt"))) { // open file foobar.txt
String line;
while ((line = br.readLine()) != null) { //read file line by line in a loop
if(line.contains(word)) { // check if line contain that word then prints the line
System.out.println(line);
}
}
}
}
}
添加回答
举报