Carriage returns/line breaks with \n in strings in Android

27,721

Solution 1

Its better to use

String lineSep = System.getProperty("line.separator");

Solution 2

Yes, the line separator under Windows is \r\n (CR+LF), on Mac \r and on Linux (Android) \n. Java has a clever reader which returns the line without separator, and a println which uses the platform setting System.getProperty("line.separator").

Solution 3

1 - like the two people before me I say, System.getProperty("line.separator") is your friend.

2 - As android is based on linux it is most likely that the line.separator property is in fact \n

3 - When reading or writing your files use buffered reader and writer an respectively their methods readLine and newLine. You should not have any trouble dealing with input/output files from/for other platforms.

Share:
27,721
Maxim Zaslavsky
Author by

Maxim Zaslavsky

I'm a computer science student at Princeton University, originally from San Diego, CA. I use machine learning to approach problems in biology and healthcare. My current research applies machine learning to immunology. I wrote my first app (a VB6-powered word-search solver) when I was 7, and I've been hooked on programming ever since. I discovered and got involved in the Stack Overflow community in 2009 (when I was 12). Check out my website for more information or to get in touch.

Updated on October 07, 2020

Comments

  • Maxim Zaslavsky
    Maxim Zaslavsky over 3 years

    I'm writing an Android app where I'm writing a file to disk with one data value per line. Later, such files can be read back into the app, and this simple data format is deserialized back into an array. At the moment, I'm delineating data values/lines in the serialization and deserialization code with \n.

    How does Android handle carriage returns and such line breaks? Can I use \n safely in this context?

  • Dan W
    Dan W over 11 years
    Wikipedia says the newer Macs (OS X) use \n like Linux. See: en.wikipedia.org/wiki/Newline
  • Joop Eggen
    Joop Eggen over 11 years
    And the 0x15 character, EBCDIC NEL, is also considered a newline.