java - 使用 %n 作为新行

标签 java newline

正如本文中所推荐的:
https://stackoverflow.com/a/38077906/12340711

It's better to use %n as an OS independent new-line character instead of \n and it's easier than using System.lineSeparator()

但是,该功能对我不起作用:

\n:

System.out.println("foo\nbar");
>>>foo
>>>bar

正常工作。

%n:

System.out.println("foo%nbar");
>>>foo%nbar

不被解释。

有人可以解释一下为什么 %n 对我不起作用吗?它是否可能不再受支持或者我错过了什么?

最佳答案

Java 为您提供了 System.lineSeparator() 常量。如果您使用 println,这将以独立于操作系统的方式中断该行。如果您只是在玩代码,您也可以在字符串中使用 \n 来换行。这既简单又快捷。请注意,println 仅将纯文本打印到控制台。

当您使用printf时,您实际上将使用java.util.Formatter来格式化字符串在控制台输出之前java.util.Formatter 的所有详细信息可以在(Java 8 文档链接)找到:https://docs.oracle.com/javase/8/docs/api/java/util/Formatter.html

因此,如果您想使用 println 格式化字符串,则需要首先使用 java.util.Formatter 对其进行格式化,如下所示:

String formattedStr = String.format("%s = %d %n hello", "joe", 35);
System.out.println(formattedStr);

其中 %s 是字符串,%d 是整数,%n 是换行符(在上面的文档链接中进行了描述) .

printf 只是上述两行代码的快捷方式,其中 String.format 已经在 printf 实现中。

System.out.printf("%s = %d %n hello", "joe", 35);

您还可以在 printf 字符串中使用 \n:

System.out.printf("%s = %d \n hello", "joe", 35);

最后,重要的是您要了解,在现实世界的项目中,如果您不使用java.util.Formatter(在 Formatter 中,使用 %n)。另外,您永远不应该在实际项目中使用 System.out.*。请改用日志记录框架。

关于java - 使用 %n 作为新行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61050018/

相关文章:

java - 根据我当前的位置每秒更新 TextView

excel - 在 Excel 2007 中导入带换行符的 CSV

excel - 为 Excel 生成 CSV 文件,如何在值内添加换行符

windows - 如何在批处理文件中回显换行符?

java - 在 SWT Eclipse 中访问树的子项

java - 从包含图像和文本的 html 生成 PDF

java - 检查电子邮件是否在数据库中,否则将用户名和密码存储在数据库中

java - 扫描 Int 时遇到问题

c# - 在 asp.net 代码隐藏页面中添加 <br/> 和 <hr/>

html - 减小 TinyMCE 文本区域中的行间距