换行符用\n还是%n?
前几天看代码时发现格式化输出时换行符使用的是“%n”,而不是“\n“,我觉得很奇怪,换行符不应该用\n么?
原来官方的解释是这样的:
A new line character appropriate to the platform running the application. You should always use %n, rather than \n.
换行符在不同系统的表示
linux 是 \n
mac 是\r
windows是 \r\n
所以使我们的代码真正的跨平台,在格式化输出时若要使用换行符一定要使用%n,例如
System.out.printf("%s-%s%n", str1, str2);
这样的形式。
例外情况
但是如果在web应用中想要格式化输出换行时,就要使用printf(\n)了。
使用%n的原因
附上orcle的官方链接:
Format
网友评论