Is there a Newline constant defined in Java like Environment.Newline in C#?

Java

Java Problem Overview


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

Is there anything similar in Java?

Java Solutions


Solution 1 - Java

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.

Solution 2 - Java

As of Java 7:

System.lineSeparator()

> http://docs.oracle.com/javase/7/docs/api/java/lang/System.html#lineSeparator%28%29"><B>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".

Solution 3 - Java

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionorjView Question on Stackoverflow
Solution 1 - JavaTom LokhorstView Answer on Stackoverflow
Solution 2 - JavaJ.SteveView Answer on Stackoverflow
Solution 3 - JavaAlan MooreView Answer on Stackoverflow