try (Stream<String> lines = Files.lines(targetFile)) {
List<String> replacedContent = lines.map(line ->
StringUtils.replaceEach(line,keys, values))
.parallel()
.collect(Collectors.toList());
Files.write(targetFile, replacedContent);
}
I'm trying to replace multiple text patterns in each line of the file. But I'm observing that "\r\n"(byte equivalent 10 and 13) is being replaced with just "\r"(just 10) and my comparison tests are failing.
I want to preserve the newlines as they are in the input file and don't want java to touch them. Could anyone suggest if there is a way to do this without having to use a separate default replacement for "\r\n".
line
wherekeys
are found.keys
are replaced withvalues
. and theseline
s are from a file -targetFile
. I generate a list of strings and write them all to a file. – Osana"\r\n"
… is being replaced with just"\r"
”. The question is where that does happen as streams don't do that. The string produced byFiles.lines
don’t have any line breaks at all. – MagnetonFiles.write()
adds "end of line" characters as it writes each "line" from the given list. The precise "end of line" sequence used is dependent on the OS you are using. Since you see only"\r"
, I guess you are on Mac OS. – UrediumFiles.write
can write a list of strings as lines and will add the system specific line break for each line. On Windows, it should be the desired\r\n
sequence. – Magneton