Java 是否支持多行字符串?

2022-08-31 04:15:24

来自Perl,我肯定缺少在源代码中创建多行字符串的“here-document”方法:

$string = <<"EOF"  # create a three-line string
text
text
text
EOF

在Java中,我必须在每行上都有繁琐的引号和加号,因为我从头开始连接我的多行字符串。

有哪些更好的选择?在属性文件中定义我的字符串?

编辑:两个答案说StringBuilder.append()比加号更可取。谁能详细说明他们为什么这么认为?对我来说,它看起来一点也不可取。我正在寻找一种方法来解决多行字符串不是一等语言构造的事实,这意味着我绝对不想用方法调用替换一等语言构造(字符串连接与加号)。

编辑:为了进一步澄清我的问题,我根本不关心性能。我担心可维护性和设计问题。


答案 1

注意:此答案适用于 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()%nString.format

另一种选择是将资源放在文本文件中,然后只读取该文件的内容。这对于非常大的字符串是可取的,以避免不必要的类文件膨胀。


答案 2

在 Eclipse 中,如果您打开“粘贴到字符串文本时转义文本”选项(在“首选项”中> Java > 编辑器>键入)并粘贴多行字符串,它将自动添加和用于所有行。"\n" +

String str = "paste your text here";