I have found many ways to replace particular file line content using Java and it worked fine up to certain data. When line contains special characters, IOUtils.write()
method fails to replace those content. I'm using latest Java 1.8. Same method works fine if I use simple replacements like replaceAll FAILED to PASSED. For e.g.
Actual file content:
23/350 | (PASSED) com.yahoo.getMail_01() | 11.21
23/350 | (FAILED) com.yahoo.getMail_02() | 11.22
23/350 | (PASSED) com.yahoo.getMail_03() | 11.23
Expected file content:
23/350 | (PASSED) com.yahoo.getMail_01() | 11.21
23/350 | (PASSED) com.yahoo.getMail_02() | 11.22
23/350 | (PASSED) com.yahoo.getMail_03() | 11.23
Tried code:
try {
content = IOUtils.toString(new FileInputStream(sFilePath), Charset.forName("UTF-8"));
} catch (FileNotFoundException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
// Here yahooGetMailPath value can be com.yahoo.getMail_02()
// Replacing PASSED to FAILED is showing just as an example.
// (PASSED) can be anything else too because its dynamic value.
content = content.replaceAll(
"(PASSED) " + yahooGetMailPath,
"(FAILED) " + yahooGetMailPath);
try {
IOUtils.write(content, new FileOutputStream(sFilePath), Charset.forName("UTF-8"));
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}