0

我找到了许多使用 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();
}
4

0 回答 0