Replace text in a file using Stream- Java 8
Using filter
eliminates anything that doesn't match the filter from the stream. (Additionally, for what it's worth, a) you only need to use parallel
once, b) parallel
isn't that effective on streams coming from I/O sources, c) it's almost never a good idea to use parallel
until you've actually tried it non-parallel and found it too slow.)
That said: there's no need to filter out the lines that match the pattern if you're going to do a replaceAll
. Your code should look like this:
try (Stream<String> lines = Files.lines(targetFile)) {
List<String> replaced = lines
.map(line-> line.replaceAll(plainTextPattern, replaceWith))
.collect(Collectors.toList());
Files.write(targetFile, replaced);
}
So sorry to tell you that this is not how files work. If you want to write to the middle of a file, you need to have RandomAccess
; Get a FilePointer
, seek, that pointer, and write from there.
This holds if the size of data you want write is equal to the size of data you want to overwrite. If this is not the case, you have to copy the tail of the file to a temp buffer and append it to the text you wish to write.
And btw, parallelStreams
on IO
bound tasks is often a bad idea.