0

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();
}
halfer
  • 19,824
  • 17
  • 99
  • 186
Jitesh Sojitra
  • 3,655
  • 7
  • 27
  • 46
  • 1
    if you want to replace FAILED to PASSED as per your expected output then shouldnt it be content = content.replaceAll( "(FAILED) " + yahooGetMailPath, "(PASSED) " + yahooGetMailPath); instead – Mudassar Nov 12 '17 at 12:30
  • 2
    Don't use replaceAll. Use replace. replaceAll expects a regexp, not a literal string. – JB Nizet Nov 12 '17 at 12:31
  • This is just an example to show, that value is dynamic and can be anything and need to tackle through code. – Jitesh Sojitra Nov 12 '17 at 12:31
  • Please improve your question. First, you have not specified what you mean by "fails". Do you get errors? Second, I doubt that the problem is in `IOUtils`, but if it is, `IOUtils` is not a standard Java class. You'll need to add its source to your question, link to its documentation, or use standard library classes instead. Third, have you checked with a debugger whether the result of your replacement was correct before calling `IOUtils.write`? – RealSkeptic Nov 12 '17 at 12:37
  • @JB Nizet, i tried replacing replaceAll to replace but it doesn't replace the values. @ Real fail means it doesn't replace the values. I think i have already mentioned that, it works if i just use simple text replacement for e.g. PASSED to FAILED. – Jitesh Sojitra Nov 12 '17 at 12:40
  • 1
    Show us a complete minimal example, with hardcoded inputs, that reproduces the problem. – JB Nizet Nov 12 '17 at 12:42

0 Answers0