java - 如何获取找到该单词的行号?
问题描述
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中使用流来计算但很困惑。你有什么主意吗?
解决方案
您可以使用 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;
}
推荐阅读
- python - PyUSB Linux USB 设备被内核回收
- php - php中的stream_socket_*和socket有什么区别?
- ios - 如何在 iPhone X 中通过 *ngIf 显示隐藏按钮
- php - 在现有 Drupal 7 中找不到管理 URL
- pandas - 如何从示例数据帧的 created_time 列中获取小时数并将其计数为另一个数据帧
- javascript - 将嵌套数组覆盖到同一个对象中
- python - 如何将 pandas.core.series.Series 和 numpy.int32 合并到 pandas.core.frame.DataFrame?
- react-native - 可以这样堆叠搜索结果吗?
- python - 如何在 python 中正确填充 4d 数组/矩阵?
- php - CodeIgniter 控制器中的函数(download_report())在本地机器上运行,但在服务器上不运行