[英]Java: Search a word in multiple files
Basically, i need to check for a word's occurances within multiple files. 基本上,我需要检查多个文件中单词的出现情况。
Also, a word might exist in a single text file multiple times. 同样,一个单词可能在单个文本文件中多次存在。
I want to save positions of a word for each file; 我想为每个文件保存一个单词的位置; so i wrote the code below: 所以我写了下面的代码:
public static void findWord(String word, File file){
try{
BufferedReader input = new BufferedReader(
new InputStreamReader(
new FileInputStream(file)));
String line;
ArrayList<Integer> list=new ArrayList<Integer>();
while((line=input.readLine())!=null){
if(line.indexOf(word)>-1){
list.add(line.indexOf(word));
}
}
System.out.println(file +": "+ list);
input.close();
}
catch(Exception ex){
ex.printStackTrace();
}
}
My code fails to add to list after first successful occurance. 第一次成功发生后,我的代码无法添加到列表中。 So I have only one element within every array. 因此,每个数组中只有一个元素。
How do i fix it? 我如何解决它?
PS My text files consists of one line PS我的文本文件由一行组成
Here goes the fix (replace your while loop with this): 解决方法如下(用以下方法替换while循环):
while ((line = input.readLine ()) != null)
{
int index = -1;
while ((index = line.indexOf (word, index + 1) > -1)
{
list.add (index);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.