title: Replace text in a file using Stream- Java 8
body: <p>I'm trying to write an API to replace all the lines containing a certain substring with a different string in a text file. </p>
  
  <p>I’m using Java 8 stream to filter the lines which contains the given pattern. I’m having problem with the file write part.</p>
  
  <pre><code>Files.lines(targetFile).filter(line -&gt; line.contains(plainTextPattern)).parallel()
        .map(line-&gt; line.replaceAll(plainTextPattern, replaceWith)).parallel();
  </code></pre>
  
  <p>Above code reads the file line-wise, filters the lines that match the pattern and replaces with the give string and gives back a stream of strings which has only the replaced lines.</p>
  
  <p>We need to write these lines back to file. Since we lose the stream once the pipeline ends, I appended the following to the pipeline:</p>
  
  <pre><code>.forEach(line -&gt; {
  try {
              Files.write(targetFile, line.toString().getBytes());
  } catch (IOException e) {
    e.printStackTrace();
  }
  </code></pre>
  
  <p>I was hoping it would write to the file only the modified (since it is in the pipeline) line and keep the other lines untouched. </p>
  
  <p>But it seems to truncate the file for each line in the file and keep only the last processed line and deletes all the lines that were not matched in the pipeline.</p>
  
  <p>Is there something I’m missing about handling files using streams?</p>