在c#中有一个静态属性Environment。根据运行平台而改变的换行符。

Java中有类似的东西吗?


从Java 7(和Android API级别19)开始:

System.lineSeparator()

文档:Java Platform SE 7


对于旧版本的Java,请使用:

System.getProperty("line.separator");

其他属性请参见https://java.sun.com/docs/books/tutorial/essential/environment/sysprop.html。


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.

当你编写文本时,你应该更关心文件将如何使用,而不是你运行在什么平台上。例如,如果你希望人们在Windows记事本中读取文件,你应该使用\r\n,因为它只识别一种分隔符。


从Java 7开始:

System.lineSeparator()

Java API: System.lineSeparator 返回系统相关的行分隔符字符串。它总是返回 相同的值-系统属性的初始值 line.separator。在UNIX系统上,它返回"\n";在微软视窗上 系统返回“\r\n”。