Question

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?
P.S My text files consists of one line

Was it helpful?

Solution

Here goes the fix (replace your while loop with this):

while ((line = input.readLine ()) != null)
{
    int index = -1;
    while ((index = line.indexOf (word, index + 1) > -1)
    {
        list.add (index);
    }
}

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top