I'm trying to write an API to replace all the lines containing a certain substring with a different string in a text file.
I’m using Java 8 stream to filter the lines which contains the given pattern. I’m having problem with the file write part.
Files.lines(targetFile).filter(line -> line.contains(plainTextPattern)).parallel()
.map(line-> line.replaceAll(plainTextPattern, replaceWith)).parallel();
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.
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:
.forEach(line -> {
try {
Files.write(targetFile, line.toString().getBytes());
} catch (IOException e) {
e.printStackTrace();
}
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.
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.
Is there something I’m missing about handling files using streams?