Search code examples
foreachjava-8locationjava-streamlines

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


I don't know if is it possible:

I want to know the number line's where someWord is found in someFile.

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

How I can to do this?


Solution

  • You don't necessarily need Stream for this or java-8... there is LineNumberReader that extends BufferedReader, so you could do:

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