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

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

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

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

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

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


当前回答

我至少看到了一种应该避免使用外部文件处理长字符串的情况:如果这些长字符串是单元测试文件中的预期值,因为我认为测试应该始终以一种不依赖任何外部资源的方式编写。

其他回答

    import org.apache.commons.lang3.StringUtils;

    String multiline = StringUtils.join(new String[] {
        "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",
        }, "\n");

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

String str = "paste your text here";

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

参见Java Stringfier。如果需要,将文本转换为StringBuilder java块转义。

使用这个库

https://github.com/alessio-santacroce/multiline-string-literals

可以这样写

System.out.println(newString(/*
      Wow, we finally have
      multiline strings in
      Java! HOOO!
*/));

很好很简单,但是只适用于单元测试