Search code examples
javafilebufferedwriter

Java write escaped characters into file


I'm writing to a file and I need to escape some characters like a quotation mark.

File fout = new File("output.txt");
try (FileOutputStream fos = new FileOutputStream(fout); BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fos));) {
    String insert = "quote's";
    s += "'"+insert.replaceAll("'", "\\\'")+"'";
    bw.write(s.replaceAll("\r\n", "\\\r\\\n"));
    bw.newLine();
}

I'm trying to acheive writing 'quote\'s' to the file but it keeps removing the backslash and producing 'quote's'

I also want to write newlines into the file as the escaped character i.e instead of inserting a newline in file I want to write \r\n

Is this possible. I feel like I'm missing/forgetting something.


Solution

  • replaceAll() works with regex and accepts a special replacement syntax:

    Note that backslashes (\) and dollar signs ($) in the replacement string may cause the results to be different than if it were being treated as a literal replacement string

    You're not using regex, so you can use the plaintext replace() instead. And you only need 2 backslashes at a time:

    s += "'"+insert.replace("'", "\\'")+"'";
    bw.write(s.replace("\r\n", "\\r\\n"));