Java Multi-line String – Java多行字符串

最后修改: 2019年 7月 3日

中文/混合/英文(键盘快捷键:t)

1. Overview

1.概述

In this tutorial, we’ll learn how to declare multiline strings in Java.

在本教程中,我们将学习如何在Java中声明多行字符串。

Now that Java 15 is out, we can use the new native feature called Text Blocks.

现在Java 15出来了,我们可以使用新的本地功能,即文本块。

We’ll also review other methods if we can’t use this feature.

如果我们不能使用这个功能,我们也会审查其他方法。

2. Text Blocks

2.文本块

We can use Text Blocks by declaring the string with “”” (three double quote marks):

我们可以使用文本块,用“”(三个双引号)声明字符串。

public String textBlocks() {
    return """
        Get busy living
        or
        get busy dying.
        --Stephen King""";
}

It is by far the most convenient way to declare a multiline string. Indeed, we don’t have to deal with line separators or indentation spaces, as noted in our dedicated article.

这是迄今为止声明多行字符串的最方便的方式。事实上,我们不必处理行的分隔符或缩进空间,正如我们的专用文章中所指出的。

This feature is available in Java 15, but also Java 13 and 14 if we enable the preview feature.

该功能在Java 15中可用,但如果我们启用预览功能,Java 13和14也可用。

In the following sections, we’ll review other methods that are suitable if we use a previous version of Java or if Text Blocks aren’t applicable.

在下面的章节中,我们将回顾其他方法,如果我们使用以前的Java版本或者Text Blocks不适用的话,这些方法是合适的。

3. Getting the Line Separator

3.获得分线器

Each operating system can have its own way of defining and recognizing new lines.

每个操作系统都可以有自己的方式来定义和识别新行。

In Java, it’s very easy to get the operating system line separator:

在Java中,要获得操作系统的分线器是非常容易的。

String newLine = System.getProperty("line.separator");

We’re going to use this newLine in the following sections to create multiline strings.

我们将在以下章节中使用这个newLine来创建多行字符串。

4. String Concatenation

4.字符串连接

String concatenation is an easy native method that can be used to create multiline strings:

字符串连接是一种简单的本地方法,可用于创建多行字符串。

public String stringConcatenation() {
    return "Get busy living"
            .concat(newLine)
            .concat("or")
            .concat(newLine)
            .concat("get busy dying.")
            .concat(newLine)
            .concat("--Stephen King");
}

Using the + operator is another way to achieve the same thing.

使用+运算符是实现同样目的的另一种方法。

Java compilers translate concat() and the + operator in the same way:

Java编译器以同样的方式翻译concat()和+运算符。

public String stringConcatenation() {
    return "Get busy living"
            + newLine
            + "or"
            + newLine
            + "get busy dying."
            + newLine
            + "--Stephen King";
}

5. String Join

5.字符串连接

Java 8 introduced String#join, which takes a delimiter along with some strings as arguments.

Java 8引入了String#join,它将一个分隔符与一些字符串作为参数。

It returns a final string having all input strings joined together with the delimiter:

它返回一个最终的字符串,所有输入的字符串用分隔符连在一起。

public String stringJoin() {
    return String.join(newLine,
                       "Get busy living",
                       "or",
                       "get busy dying.",
                       "--Stephen King");
}

6. String Builder

6.字符串生成器

StringBuilder is a helper class to build Strings. StringBuilder was introduced in Java 1.5 as a replacement for StringBuffer.

StringBuilder是一个用于构建String的辅助类。StringBuilder是在Java 1.5中引入的,作为StringBuffer的替代。

It’s a good choice for building huge strings in a loop:

这是一个很好的选择,可以在一个循环中建立巨大的字符串。

public String stringBuilder() {
    return new StringBuilder()
            .append("Get busy living")
            .append(newLine)
            .append("or")
            .append(newLine)
            .append("get busy dying.")
            .append(newLine)
            .append("--Stephen King")
            .toString();
}

7. String Writer

7.字符串写入器

StringWriter is another method that we can utilize to create a multiline string. We don’t need newLine here because we use PrintWriter.

StringWriter是另一种方法,我们可以利用它来创建一个多行字符串。我们在这里不需要newLine,因为我们使用PrintWriter

The println function automatically adds new lines:

println函数自动添加新行。

public String stringWriter() {
    StringWriter stringWriter = new StringWriter();
    PrintWriter printWriter = new PrintWriter(stringWriter);
    printWriter.println("Get busy living");
    printWriter.println("or");
    printWriter.println("get busy dying.");
    printWriter.println("--Stephen King");
    return stringWriter.toString();
}

8. Guava Joiner

8.番石榴加盟店

Using an external library just for a simple task like this doesn’t make much sense. However, if the project already uses the library for other purposes, we can utilize it.

仅仅为了这样一个简单的任务而使用一个外部库并没有什么意义。然而,如果该项目已经将该库用于其他目的,我们可以利用它。

For example, Google’s Guava library is very popular.

例如,谷歌的Guava库就非常受欢迎。

Guava has a Joiner class that is able to build multiline strings:

Guava有一个Joiner,能够构建多行字符串。

public String guavaJoiner() {
    return Joiner.on(newLine).join(ImmutableList.of("Get busy living",
        "or",
        "get busy dying.",
        "--Stephen King"));
}

9. Loading From a File

9.从文件加载

Java reads files exactly as they are. This means that if we have a multiline string in a text file, we’ll have the same string when we read the file. There are a lot of ways to read from a file in Java.

Java完全按照文件的原样读取文件。这意味着,如果我们在文本文件中拥有一个多行字符串,那么当我们读取文件时,我们将拥有相同的字符串。有很多方法可以在Java中从文件中读取

It’s actually a good practice to separate long strings from code:

实际上,将长字符串与代码分开是一个好的做法。

public String loadFromFile() throws IOException {
    return new String(Files.readAllBytes(Paths.get("src/main/resources/stephenking.txt")));
}

10. Using IDE Features

10.使用IDE的功能

Many modern IDEs support multiline copy/paste. Eclipse and IntelliJ IDEA are examples of such IDEs. We can simply copy our multiline string and paste it inside two double quotes in these IDEs.

许多现代IDE支持多行复制/粘贴。Eclipse和IntelliJ IDEA就是这种IDE的例子。我们可以简单地复制我们的多行字符串,并在这些IDE中把它粘贴在两个双引号内。

Obviously, this method doesn’t work for string creation in runtime, but it’s a quick and easy way to get a multiline string.

很明显,这个方法在运行时对字符串的创建不起作用,但这是一个快速和简单的方法来获得多行字符串。

11. Conclusion

11.结论

In this article, we learned several methods to build multiline strings in Java.

在这篇文章中,我们学习了几种在Java中建立多行字符串的方法。

The good news is that Java 15 has native support for multiline strings via Text Blocks.

好消息是,Java 15通过Text Blocks对多行字符串提供了本地支持。

All the other methods reviewed can be used in Java 15 or any previous version.

所有其他审查的方法都可以在Java 15或以前的任何版本中使用。

The code for all the methods in this article is available over on GitHub.

本文中所有方法的代码都可以在GitHub上找到over