是否有像 C# 中的 Environment.Newline 这样的 Java 中定义的换行符常量?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/247059/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Is there a Newline constant defined in Java like Environment.Newline in C#?
提问by orj
In C# there is the static property Environment.Newlinethat changed depending on the running platform.
在 C# 中,有静态属性Environment.Newline根据运行平台而变化。
Is there anything similar in Java?
Java中有没有类似的东西?
采纳答案by Tom Lokhorst
As of Java 7 (and Android API level 19):
从 Java 7(和 Android API 级别 19)开始:
System.lineSeparator()
Documentation: Java Platform SE 7
文档:Java 平台 SE 7
For older versions of Java, use:
对于旧版本的 Java,请使用:
System.getProperty("line.separator");
See https://java.sun.com/docs/books/tutorial/essential/environment/sysprop.htmlfor other properties.
有关其他属性,请参阅https://java.sun.com/docs/books/tutorial/essential/environment/sysprop.html。
回答by Alan Moore
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 机器上运行,并不意味着它正在读取的文件将使用 Windows 样式的行分隔符。许多网页混合了“\n”和“\r\n”,它们是从不同的来源拼凑而成的。当您将文本作为一系列逻辑行阅读时,您应该始终寻找所有三种主要的行分隔符样式:Windows ("\r\n")、Unix/Linux/OSX ("\n") 和OSX 之前的 Mac(“\r”)。
When you're writingtext, 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.
当您编写文本时,您应该更关心文件的使用方式,而不是您正在运行的平台。例如,如果您希望人们在 Windows 记事本中阅读文件,您应该使用“\r\n”,因为它只识别一种分隔符。
回答by J.Steve
As of Java 7:
从 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".
返回系统相关的行分隔符字符串。它总是返回相同的值——系统属性 line.separator 的初始值。在 UNIX 系统上,它返回“\n”;在 Microsoft Windows 系统上,它返回“\r\n”。