\n and \r seem to work everywhere. Why is line.separator more portable?

java, linefeed, newline, portability

Solution

Incorrect line endings are a frequent annoyance. For example, this is what Windows Notepad shows when writing a file with `\n` instead of `\r\n` (Windows' line.separator):

Those little boxes were supposed to be line breaks.

The other way around, when `\r\n` is used in place of `\n` (Unix' line.separator), is way worse, and breaks shell scripts and config files in weird and wonderful ways.

For example, this is what `sh` outputs on Debian and derived distros when trying to run a shell script that just contains `ls` but with `\r\n` line separators (it looks trashed because the carriage return causes the terminal to overwrite parts of the line):

: not foundsh: ls

There are several questions per day on StackOverflow from people being bitten by this, such as here, here and here.

Problem

I was just perusing through questions, and I found `System.getProperty(line.separator)` used in place of `\n` with the author's comment that the code was "portable". Reading through various forums, I've seen two groups: - People who say there's a difference between Linux's and Windows' interpretation of newline characters, and this compensates for that (with no clear evidence). - People who say there's no difference by showing code and output examples, which obviously only applies to that code example and not universally. My feeling is: it's probably non-standard OS's, like for example your company's industrial scanner's OS for example, where you'll notice a difference. When am I going to see a difference between `\n` and `line.separator`? Can you show an example, please? How did you go about discovering where the variation occurs?

Original source