0

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.

4
  • 2
    Change replaceAll() to replace(). Commented Nov 28, 2022 at 22:17
  • @shmosel that works! thanks. Care to detail an explanation ? Commented Nov 28, 2022 at 22:20
  • System.out.println("Hell'o, Wor'ld!".replaceAll("'", "\\\\'")); will print Hell\'o, Wor\'ld! Commented Nov 28, 2022 at 22:21
  • replaceAll handle regular expression. Including the replace part, as example System.out.println("Hello!".replaceAll("(ll)", "$1o$1")); this will result Hellollo! Commented Nov 28, 2022 at 22:27

1 Answer 1

1

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"));
Sign up to request clarification or add additional context in comments.

3 Comments

you do not need "\\\'", instead use \\'
That's true, single quotes don't have to be escaped.
OP says "instead of inserting a newline in file I want to write \r\n". But your code does not.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.