我找到了许多使用Java替换特定文件行内容的方法,它可以很好地处理某些数据。当行包含特殊字符时,IOUtils.write()
方法无法替换这些内容。我正在使用最新的Java 1.8。如果我使用像replaceAll FAILED to PASSED这样的简单替换,同样的方法也能正常工作。例如,
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
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
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();
}