Java 8:应用过滤器时的行位置出现,流,foreach

时间:2018-03-16 21:25:54

标签: foreach java-8 location java-stream lines

我不知道是否可能:

我想知道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);
    }

我该怎么做?

2 个答案:

答案 0 :(得分:2)

您可以收集到列表,而不是在br.lines()上管理进一步的操作,然后使用IntStream.range,如下所示:

...
...
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));
...
...

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

答案 1 :(得分:0)

你不一定需要Stream for this或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())
       }
   }