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

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

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

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

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

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


当前回答


注意:这个答案适用于Java 14及以上版本。

Java 15引入了文本块(多行文字)。详情请看这个答案。


听起来像是要做一个多行文字,这在Java中是不存在的。

你最好的选择是用+ d组合的字符串。人们提到的一些其他选项(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(),要么可以在String.format中使用%n。

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

其他回答

由于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

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

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

你可以在一个单独的方法中连接你的追加:

public static String multilineString(String... lines){
   StringBuilder sb = new StringBuilder();
   for(String s : lines){
     sb.append(s);
     sb.append ('\n');
   }
   return sb.toString();
}

无论哪种方式,都更喜欢StringBuilder而不是加号符号。

遗憾的是,Java没有多行字符串字面量。您要么必须连接字符串字面量(使用+或StringBuilder是最常见的两种方法),要么从单独的文件中读取字符串。

对于大的多行字符串文字,我倾向于使用一个单独的文件,并使用getResourceAsStream() (Class类的一个方法)读取它。这使得查找文件变得很容易,因为您不必担心当前目录与代码安装的位置。它还使打包更容易,因为您实际上可以将文件存储在jar文件中。

假设你在一个名为Foo的类中。就像这样做:

Reader r = new InputStreamReader(Foo.class.getResourceAsStream("filename"), "UTF-8");
String s = Utils.readAll(r);

另一个烦恼是Java没有标准的“将这个Reader中的所有文本读入字符串”方法。写起来很简单:

public static String readAll(Reader input) {
    StringBuilder sb = new StringBuilder();
    char[] buffer = new char[4096];
    int charsRead;
    while ((charsRead = input.read(buffer)) >= 0) {
        sb.append(buffer, 0, charsRead);
    }
    input.close();
    return sb.toString();
}

一个不错的选择。

import static some.Util.*;

    public class Java {

        public static void main(String[] args) {

            String sql = $(
              "Select * from java",
              "join some on ",
              "group by"        
            );

            System.out.println(sql);
        }

    }


    public class Util {

        public static String $(String ...sql){
            return String.join(System.getProperty("line.separator"),sql);
        }

    }

这是一个老线程,但是一个新的非常优雅的解决方案(只有4个或3个小缺点)是使用自定义注释。

查询:http://www.adrianwalker.org/2011/12/java-multiline-string.html

受此启发的一个项目托管在GitHub上:

https://github.com/benelog/multiline

Java代码示例:

import org.adrianwalker.multilinestring.Multiline;
...
public final class MultilineStringUsage {

  /**
  <html>
    <head/>
    <body>
      <p>
        Hello<br/>
        Multiline<br/>
        World<br/>
      </p>
    </body>
  </html>
  */
  @Multiline
  private static String html;

  public static void main(final String[] args) {
    System.out.println(html);
  }
}

缺点是

您必须激活相应的(提供的)注释 处理器。 该字符串变量不能定义为局部变量检查原始字符串字面量项目,其中您可以将变量定义为局部变量 字符串不能像在Visual Basic .Net中那样包含其他变量 使用XML文本(<%=变量%>):-) 字符串文字由JavaDoc注释(/**)分隔

而且您可能必须配置Eclipse/Intellij-Idea,使其不会自动重新格式化Javadoc注释。

有人可能会觉得这很奇怪(Javadoc注释并不是为嵌入注释以外的任何内容而设计的),但由于Java中缺少多行字符串确实令人讨厌,因此我认为这是最不糟糕的解决方案。