1

Is there a quick way to replace all occurrences of a given character in a file (the whole file at once) for another?

I wonder if this could be done in a global way or something, without reading it line by line.

in my specific case, I want to replace pipes (|) for commas (,).

Shoe
  • 74,840
  • 36
  • 166
  • 272
filippo
  • 5,583
  • 13
  • 50
  • 72

1 Answers1

2

Simply retrieve the text from the file and then use string.replaceAll("\\|", ",");

Here is an example using the code from erickson's answer:

private static String readFile(String path) throws IOException {
  FileInputStream stream = new FileInputStream(new File(path));
  try {
    FileChannel fc = stream.getChannel();
    MappedByteBuffer bb = fc.map(FileChannel.MapMode.READ_ONLY, 0, fc.size());
    /* Instead of using default, pass in a decoder. */
    return Charset.defaultCharset().decode(bb).toString();
  }
  finally {
    stream.close();
  }
}

You can use it like this:

String replacedTxt = readFile(path).replaceAll("\\|", ",");
Community
  • 1
  • 1
0x6C38
  • 6,796
  • 4
  • 35
  • 47