Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

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

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading