我在讀取txt文件時遇到問題,並使用java的scanner.util查找單詞/模式。 目前正在測試閱讀,我收到每行的盈方。在這個問題之後,我仍然不確定如何搜索txt文件中的模式/單詞。我還必須顯示包含模式/單詞的行。掃描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);
}
}
}
你先回答並解決了我的問題,但其他人回答得更詳細,這有助於我進一步理解。非常感謝您的支持,並非常抱歉,您會因爲這樣的noob問題而煩惱您。 – 2013-02-13 05:19:17