227

In C# there is the static property Environment.Newline that changed depending on the running platform.

Is there anything similar in Java?

orj
  • 13,234
  • 14
  • 63
  • 73

3 Answers3

329

As of Java 7 (and Android API level 19):

System.lineSeparator()

Documentation: Java Platform SE 7


For older versions of Java, use:

System.getProperty("line.separator");

See https://java.sun.com/docs/books/tutorial/essential/environment/sysprop.html for other properties.

Tom Lokhorst
  • 13,658
  • 5
  • 55
  • 71
93

As of Java 7:

System.lineSeparator()

Java API : System.lineSeparator

Returns the system-dependent line separator string. It always returns the same value - the initial value of the system property line.separator. On UNIX systems, it returns "\n"; on Microsoft Windows systems it returns "\r\n".

J.Steve
  • 7,109
  • 2
  • 22
  • 22
70

Be aware that this property isn't as useful as many people think it is. Just because your app is running on a Windows machine, for example, doesn't mean the file it's reading will be using Windows-style line separators. Many web pages contain a mixture of \n and \r\n, having been cobbled together from disparate sources. When you're reading text as a series of logical lines, you should always look for all three of the major line-separator styles: Windows \r\n, Unix/Linux/OSX \n and pre-OSX Mac \r.

When you're writing text, you should be more concerned with how the file will be used than what platform you're running on. For example, if you expect people to read the file in Windows Notepad, you should use \r\n because it only recognizes the one kind of separator.

abatista
  • 79
  • 9
Alan Moore
  • 73,866
  • 12
  • 100
  • 156
  • 1
    Is the pre-OSX Mac ("\r") still in practical used? Or is it true to say that it can be safely "forgotten" ? – Pacerier Mar 06 '12 at 03:46
  • 7
    Well, whether or not the machines themselves are still in use, you have to assume there are still documents out there that were *written* on pre-OSX Macs. I know it's tempting to shorten `(?:\r?\n|\r)` to `(?:\r?n)`, but no, I don't think it's safe. I prefer `(?:\r\n|[\r\n])` anyway; I know it's more characters, but it looks neater. :D And if you don't care *how many* line separators you consume, `[\r\n]+` works just fine. – Alan Moore Mar 06 '12 at 10:22
  • Completely agree... there's still a place for static constants if your software targets a particular environment – Marco Pelegrini Mar 31 '21 at 15:56
  • Best answer. I have to generate a TXT file that needs to have CRLF as line separator and my webapp usually runs on Linux (not always). Using lineSeparator would not work. – Lluis Martinez Oct 28 '21 at 16:43
  • As for the writing. If you are generating an Excel file and writing a multi-line cell value where the lines are concatenated with `\n`, then in Windows, in Excel, a user will see those lines as a single line while seeing them as separate lines in Ubuntu's LibreOffce Calc. – Burst Sep 05 '22 at 07:50