首页 > 解决方案 > 如何获取找到该单词的行号?

问题描述

private static List<A> compute(Path textFile, String word) {
    List<A> results = new ArrayList<A>();

    try {
        Files.lines(textFile).forEach(line -> {

            BreakIterator it = BreakIterator.getWordInstance();
            it.setText(line.toString());

            int start = it.first();
            int end = it.next();

            while (end != BreakIterator.DONE) {
                String currentWord = line.toString().substring(start, end);
                if (Character.isLetterOrDigit(currentWord.charAt(0))) {
                    if (currentWord.equals(word)) {
                        results.add(new WordLocation(textFile, line));
                        break;
                    }
                }
                start = end;
                end = it.next();
            }
        });

    } catch (IOException e) {
        e.printStackTrace();
    }
    return results;
}

如何获取找到该单词的行号?我想在Lamda中使用流来计算但很困惑。你有什么主意吗?

标签: javajava-stream

解决方案


您可以使用 aLineNumberReader来获取行号。看起来像这样:

private static List<A> compute(Path textFile, String word) {
    List<A> results = new ArrayList<A>();

    try (final LineNumberReader reader = new LineNumberReader(new FileReader(textFile.toFile()))) {
        String line;
        while ((line = reader.readLine()) != null) {
            BreakIterator it = BreakIterator.getWordInstance();
            it.setText(line);

            int start = it.first();
            int end = it.next();

            final int lineNumber = reader.getLineNumber(); // here is your linenumber

            while (end != BreakIterator.DONE) {
                String currentWord = line.substring(start, end);
                if (Character.isLetterOrDigit(currentWord.charAt(0))) {
                    if (currentWord.equals(word)) {
                        results.add(new WordLocation(textFile, line));
                        break;
                    }
                }
                start = end;
                end = it.next();
            }
        }

    } catch (IOException e) {
        e.printStackTrace();
    }
    return results;
}

推荐阅读