Java 8: Lines Location occurrence, when filter applyed, stream, foreach

Java 8: Lines Location occurrence, when filter is applied, stream, foreach

不知道可不可以:

我想知道在 someFile 中找到 someWord 的数字行。

   try {
      CharsetDecoder dec = StandardCharsets.UTF_8.newDecoder()
          .onMalformedInput(CodingErrorAction.IGNORE);
      try (Reader r = Channels.newReader(FileChannel.open("path"), dec, -1);
          BufferedReader br = new BufferedReader(r)) {
        br.lines().filter(line -> line.contains("SomeWord"))
            .forEach(line -> System.out.println("location:" + line.????)); //Location where line has the "SomeWord"
      }
    } catch (IOException |java.io.UncheckedIOException ex) {
      Logger.getLogger(RecursiveFolderAndFiles.class.getName())
          .log(Level.SEVERE, null, ex);
    }

我该怎么做?

您可以收集到一个列表然后利用 IntStream.range,而不是对 br.lines() 进行进一步的操作:

...
...
List<String> resultSet = br.lines().collect(Collectors.toList());
IntStream.range(0, resultSet.size())
         .filter(index -> resultSet.get(index).contains("SomeWord"))
         .forEach(index -> System.out.println("location:" + index));
...
...

现在,您应该可以访问索引和行。

您不一定需要 Stream 或 java-8... LineNumberReader 扩展了 BufferedReader,因此您可以这样做:

LineNumberReader lnr = new LineNumberReader(r)) {
   String line;
   while ((line = lnr.readLine()) != null) {  
       if(line.contains("SomeWord")) {
             System.out.println("location:" + lnr.getLineNumber())
       }
   }