我在读取 txt 文件并使用 java 的scanner.util 查找单词/模式时遇到问题。目前正在测试读数,我在每一行前面都得到了空值。在那个问题之后,我仍然不确定如何在 txt 文件中搜索模式/单词。我还必须显示包含模式/单词的行。
public class SearchPattern {
public static void main(String[] args) throws IOException{
Scanner s = new Scanner(System.in);
String pattern;
String filename;
String[] text = new String[10];
System.out.println("Enter the filename");
filename = s.nextLine();
System.out.println("Enter the pattern you'd like to search");
pattern = s.nextLine();
// Print out each line that contains pattern
// may need an array to store StringS of lines with word
try{
s = new Scanner(new BufferedReader(new FileReader(filename)));
int x = 0;
while (s.hasNext()) {
text[x] += s.next();
x++;
}
}
finally {
if (s != null) {
s.close();
}
}
text[0] = "test";
System.out.println(text[0]);
for(String txt : text){
System.out.println(txt);
}
}
}