Is there a Newline constant defined in Java like Environment.Newline in C#?
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".
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.
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.