为什么" println"我们可以使用" \ n&#34 ;?

时间:2017-07-11 14:11:09

标签: java println

我是java的新手,并且想知道为什么有人会使用System.out.println()来改变行而不是仅仅放置" \ n"在括号内。这两者之间有什么不同吗?

3 个答案:

答案 0 :(得分:6)

咨询Javadoc(强调我的):

  

[PrintStream.println]通过写行分隔符字符串来终止当前行。行分隔符字符串由系统属性line.separator定义,不一定是单个换行符('\n'

例如,Windows使用\r\n作为默认换行符。

答案 1 :(得分:0)

不同操作系统中的新行不同,例如

Unix based systems=> "\n" 
windows => "\r\n" 
and some other machines used just a "\r". (Commodore, Apple II, Mac OS prior to OS X, etc..)

如果你不使用println,你必须自己管理这些,或者通过像这样的系统来获得

System.getProperty("line.separator");

答案 2 :(得分:0)

如评论中所示,仅添加\n将无法在所有环境(例如Windows)中使用。如果要追加“手动”结尾的正确行,则需要使用

检索它
 System.getProperty("line.separator");

或者,在Java 7中:

 System.lineSeparator()

另见this answer(这两行代码的来源)。

相关问题