1

I´m exporting data from a database table and writing it down in a file. Newline characters are correctly retrieved from the database and kept when writing the String (so I´m able to reimport the exported data).

My problem is that in the file the newline characters are implicit (i.e. they appear as line breaks). If the database value is the string "line1 \r\n line2", the result of directly sending this String to my BufferedWriter + FileOutputStream is "line1 line2"

Is there any way I can write to the file exactly the "line1 \r\n line2" sequence of characters? (I've already tried bw.write(value.toCharArray())

Jordi Cabot
  • 8,058
  • 2
  • 33
  • 39
  • 1
    Although they appear as line breaks (because that's what they are), the characters are still there. Programmatically load the file and display it as an array of characters to validate this, if you need the verification. – FThompson Dec 04 '12 at 05:51
  • I know the information is there (that´s why I can reimport the data in the database) but I´d like to be able to tell Java not to interpret them and just print them as part of the String as if they were normal characters (and just let the database to reinterpret them when importing the file). Otherwise the file gets too long – Jordi Cabot Dec 04 '12 at 05:55
  • You can find your answer here :[Newline character omitted while reading from buffer][1] [1]: http://stackoverflow.com/questions/4825263/newline-character-omitted-while-reading-from-buffer – Abhishek_Mishra Dec 04 '12 at 05:57
  • 1
    You'll need to do a `replaceAll` of every escape character, and escape its backslash. One example: `str.replaceAll("\n", "\\n")`. – FThompson Dec 04 '12 at 05:58
  • You're right, this should work. You may want to add this as answer instead of a comment so that I can mark it as correct – Jordi Cabot Dec 04 '12 at 06:00
  • Alright, give me a minute. I'll make it a complete answer too, handling all escape characters. – FThompson Dec 04 '12 at 06:00
  • My apologies for taking so long, I had some other obligations to attend to. Anyway, I've written the method in the most concise way I could think of, and posted it as an answer. – FThompson Dec 04 '12 at 06:30

1 Answers1

2

You can replace every escape sequence with a double-backslash:

public static String escapeChars(String str) {
    char[][] escapes = {
            { '\n', 'n' },
            { '\r', 'r' },
            { '\f', 'f' },
            { '\b', 'b' },
            { '\t', 't' }
    };
    for (char[] escape : escapes) {
        str = str.replaceAll(Character.toString(escape[0]), "\\\\" + escape[1]);
    }
    return str;
}

Double- and single-apostrophe escaping can be added easily, but I've omitted it in this answer.

FThompson
  • 28,352
  • 13
  • 60
  • 93