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

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

在Java中,当我从头开始连接多行字符串时,我必须在每一行上使用繁琐的引号和加号。

有什么更好的选择吗?在属性文件中定义我的字符串?

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

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


当前回答

如果你像我一样喜欢谷歌的番石榴,它可以提供一个相当干净的表示和一个很好的,简单的方法来不硬编码你的换行符:

String out = Joiner.on(newline).join(ImmutableList.of(
    "line1",
    "line2",
    "line3"));

其他回答

在Eclipse中,如果你打开选项“在粘贴到字符串文字时转义文本”(在Preferences > Java > Editor > Typing中)并在引号中粘贴一个多行字符串,它将自动为你的所有行添加“和\n”+。

String str = "paste your text here";

另一种方法是将长字符串存储在外部文件中,然后将文件读入字符串。

在IntelliJ IDE中,你只需要输入:

""

然后将光标放置在引号内并粘贴字符串。IDE将它扩展为多个连接的行。

使用JDK/12早期访问构建# 12,现在可以在Java中使用多行字符串,如下所示:

String multiLine = `First line
    Second line with indentation
Third line
and so on...`; // the formatting as desired
System.out.println(multiLine);

这将导致以下输出:

第一行 第二行有缩进 第三行 等等……

编辑: 推迟至java 13

这个问题有两个答案:

In you want to stick to pure Java, with Java 14 being released in March 2020, you can leverage the JEP 368 - Text Blocks, in Second Preview mode. Actually the feature is in preview mode in other releases (at least 13 has it). I created and example set here. While this feature is useful, it can be easily abused. Remember that Java requires compilation - having large character arrays in your code can be an easy way to shoot yourself in the leg (if you want a quick change, you will need recompilation - that toolset might not be available to the guy operating your application).

根据我的经验,建议在配置文件中保留大字符串(通常是应用程序操作员可以/应该在运行时更改的字符串)。

总结:负责地使用文本块:)。