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

前端 未结 3 396
面向向阳花
面向向阳花 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:34

    Read the text file using Java class LineNumberReader and call method getLineNumber to find the current line number.

    http://docs.oracle.com/javase/7/docs/api/java/io/LineNumberReader.html

    0 讨论(0)
  • 2020-12-21 14:35

    You can store this information manually. Whenever you are invoking readline() of your BufferedReader, if you're using such, you can also increment a counter by one. E.g.,

    public int grepLineNumber(String file, String word) throws Exception {
        BufferedReader buf = new BufferedReader(new InputStreamReader(new DataInputStream(new FileInputStream(file))));
    
        String line;
        int lineNumber = 0;
        while ((line = buf.readLine()) != null)   {
            lineNumber++;
            if (word.equals(line)) {
                return lineNumber;
            }
        }
        return -1;
    }
    
    0 讨论(0)
  • 2020-12-21 14:53

    Something like this might work:

    public ArrayList<Integer> find(String word, File text) throws IOException {
        LineNumberReader rdr = new LineNumberReader(new FileReader(text));
        ArrayList<Integer> results = new ArrayList<Integer>();
        try {
            String line = rdr.readLine();
            if (line.indexOf(word) >= 0) {
                results.add(rdr.getLineNumber());
            }
        } finally {
            rdr.close();
        }
        return results;
    }
    
    0 讨论(0)
提交回复
热议问题