注意:此答案适用于 Java 14 及更早版本。
文本块(多行文字)是在Java 15中引入的。有关详细信息,请参阅此答案。
这听起来像是你想做一个多行文字,这在Java中不存在。
你最好的选择是串联在一起。人们提到的其他一些选项(StringBuilder,String.format,String.join)只有在从字符串数组开始时才更可取。+
请考虑以下情况:
String s = "It was the best of times, it was the worst of times,\n"
+ "it was the age of wisdom, it was the age of foolishness,\n"
+ "it was the epoch of belief, it was the epoch of incredulity,\n"
+ "it was the season of Light, it was the season of Darkness,\n"
+ "it was the spring of hope, it was the winter of despair,\n"
+ "we had everything before us, we had nothing before us";
对:StringBuilder
String s = new StringBuilder()
.append("It was the best of times, it was the worst of times,\n")
.append("it was the age of wisdom, it was the age of foolishness,\n")
.append("it was the epoch of belief, it was the epoch of incredulity,\n")
.append("it was the season of Light, it was the season of Darkness,\n")
.append("it was the spring of hope, it was the winter of despair,\n")
.append("we had everything before us, we had nothing before us")
.toString();
对:String.format()
String s = String.format("%s\n%s\n%s\n%s\n%s\n%s"
, "It was the best of times, it was the worst of times,"
, "it was the age of wisdom, it was the age of foolishness,"
, "it was the epoch of belief, it was the epoch of incredulity,"
, "it was the season of Light, it was the season of Darkness,"
, "it was the spring of hope, it was the winter of despair,"
, "we had everything before us, we had nothing before us"
);
与 Java8 String.join() 的对比
:
String s = String.join("\n"
, "It was the best of times, it was the worst of times,"
, "it was the age of wisdom, it was the age of foolishness,"
, "it was the epoch of belief, it was the epoch of incredulity,"
, "it was the season of Light, it was the season of Darkness,"
, "it was the spring of hope, it was the winter of despair,"
, "we had everything before us, we had nothing before us"
);
如果需要为特定系统使用换行符,则需要使用 ,也可以在 中使用。System.lineSeparator()
%n
String.format
另一种选择是将资源放在文本文件中,然后只读取该文件的内容。这对于非常大的字符串是可取的,以避免不必要的类文件膨胀。