Finding line number of a word in a text file using java

前端 未结 3 398
面向向阳花
面向向阳花 2020-12-21 14:03

I require searching a word in a text file and display the line number using java. If it appears more than once I need to show all the line numbers in the output. Can anyone

3条回答
  •  孤城傲影
    2020-12-21 14:53

    Something like this might work:

    public ArrayList find(String word, File text) throws IOException {
        LineNumberReader rdr = new LineNumberReader(new FileReader(text));
        ArrayList results = new ArrayList();
        try {
            String line = rdr.readLine();
            if (line.indexOf(word) >= 0) {
                results.add(rdr.getLineNumber());
            }
        } finally {
            rdr.close();
        }
        return results;
    }
    

提交回复
热议问题