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

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

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

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

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

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


当前回答

JEP 378: Text Blocks涵盖了此功能,并且包含在JDK 15中。它最初出现在JDK 13中的JEP 355: Text Blocks(预览)和JDK 14中的JEP 368: Text Blocks(第二预览),可以在这些版本中通过——enable-preview javac选项启用。

语法允许这样写:

String s = """
           text
           text
           text
           """;

在此之前,在JDK 12中,JEP 326: Raw String Literals旨在实现类似的功能,但最终被撤回:

请注意:这原本是JDK 12中的预览语言功能,但它已被撤回,并没有出现在JDK 12中。它在JDK 13中被文本块(JEP 355)所取代。

其他回答

我还没有看到的另一个答案是java.io.PrintWriter。

StringWriter stringWriter = new StringWriter();
PrintWriter writer = new PrintWriter(stringWriter);
writer.println("It was the best of times, it was the worst of times");
writer.println("it was the age of wisdom, it was the age of foolishness,");
writer.println("it was the epoch of belief, it was the epoch of incredulity,");
writer.println("it was the season of Light, it was the season of Darkness,");
writer.println("it was the spring of hope, it was the winter of despair,");
writer.println("we had everything before us, we had nothing before us");
String string = stringWriter.toString();

此外,java.io.BufferedWriter有一个newLine()方法的事实也未被提及。

一个简单的选择是使用SciTE (http://www.scintilla.org/SciTEDownload.html)这样的编辑器编辑java代码,它允许您对文本进行WRAP,以便容易地查看和编辑长字符串。如果你需要转义字符,你只需输入它们。通过关闭“换行”选项,您可以检查字符串是否仍然是一个很长的单行字符串。当然,如果不是,编译器也会告诉你。

Eclipse或NetBeans是否支持编辑器中的文本包装,我不知道,因为它们有太多的选项。但如果没有,这将是一个很好的补充。

我有时使用一个并行groovy类来充当一个字符串包

这里的java类

public class Test {
    public static void main(String[] args) {
        System.out.println(TestStrings.json1);
        // consume .. parse json
    }
}

以及TestStrings.groovy中令人垂涎的多行字符串

class TestStrings {
    public static String json1 = """
    {
        "name": "Fakeer's Json",
        "age":100,
        "messages":["msg 1","msg 2","msg 3"]
    }""";
}

当然,这只适用于静态字符串。如果我必须在文本中插入变量,我会将整个文件更改为groovy。只要保持强类型实践,它就可以实现。

String.join

Java 8为Java .lang. string添加了一个新的静态方法,它提供了一个更好的选择:

String.join ( CharSequence分隔符, CharSequence进行…元素 )

使用它:

String s = String.join(
    System.getProperty("line.separator"),
    "First line.",
    "Second line.",
    "The rest.",
    "And the last!"
);

由于Java(还)不支持多行字符串,目前唯一的方法是使用前面提到的技术之一来破解它。我使用上面提到的一些技巧构建了下面的Python脚本:

import sys
import string
import os

print 'new String('
for line in sys.stdin:
    one = string.replace(line, '"', '\\"').rstrip(os.linesep)
    print '  + "' + one + ' "'
print ')'

把它放在一个名为javastringify.py的文件中,把你的字符串放在一个名为mystring.txt的文件中,然后像下面这样运行:

cat mystring.txt | python javastringify.py

然后,您可以复制输出并将其粘贴到编辑器中。

修改这需要处理任何特殊情况,但这是为我的需要。希望这能有所帮助!