通过Java替换文件内容包含特殊字符的某些行数据

时间:2017-11-12 12:19:46

标签: java ioutils

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

0 个答案:

没有答案