[英]Find a word in a File and print the line that contains it in java
使用命令行,我應該輸入包含文本的文件名並搜索特定單詞。
foobar 文件.txt
我開始編寫以下代碼:
import java.util.*;
import java.io.*;
class Find {
public static void main (String [] args) throws FileNotFoundException {
String word = args[0];
Scanner input = new Scanner (new File (args[1]) );
while (input.hasNext()) {
String x = input.nextLine();
}
}
}
我的程序應該找到單詞,然后打印包含它的整行。 請具體說明,因為我是 Java 新手。
您已經在讀取文件的每一行,因此使用String.contains()
方法將是您的最佳解決方案
if (x.contains(word) ...
如果給定的String
包含您傳遞給它的字符序列(或 String),則contains()
方法僅返回true
。
注:此檢查是區分大小寫的,所以如果你想檢查是否有資本的任何組合存在的話,只是字符串轉換為相同的情況下,第一:
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);
}
}
}
首先,您必須打開文件,然后逐行讀取它並檢查該單詞是否在該行中。 請參閱下面的代碼。
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);
}
}
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.