regex - Replace text in a file using Stream- Java 8 -
i'm trying write api replace lines containing substring different string in text file.
i’m using java 8 stream filter lines contains given pattern. i’m having problem file write part.
files.lines(targetfile).filter(line -> line.contains(plaintextpattern)).parallel() .map(line-> line.replaceall(plaintextpattern, replacewith)).parallel();
above code reads file line-wise, filters lines match pattern , replaces give string , gives stream of strings has replaced lines.
we need write these lines file. since lose stream once pipeline ends, appended following pipeline:
.foreach(line -> { try { files.write(targetfile, line.tostring().getbytes()); } catch (ioexception e) { e.printstacktrace(); }
i hoping write file modified (since in pipeline) line , keep other lines untouched.
but seems truncate file each line in file , keep last processed line , deletes lines not matched in pipeline.
is there i’m missing handling files using streams?
using filter
eliminates doesn't match filter stream. (additionally, it's worth, a) need use parallel
once, b) parallel
isn't effective on streams coming i/o sources, c) it's never idea use parallel
until you've tried non-parallel , found slow.)
that said: there's no need filter out lines match pattern if you're going replaceall
. code should 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); }
Comments
Post a Comment