1. 概要

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

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

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

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.

この機能はJava15で使用できますが、プレビュー機能を有効にするとJava13および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.

3. ラインセパレーターの入手

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

Javaでは、オペレーティングシステムの行区切り文字を簡単に取得できます。

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

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

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コンパイラは、 concat()と+演算子を同じ方法で変換します。

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

5. 文字列結合

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

すべての入力文字列が区切り文字で結合された最終的な文字列を返します。

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

6. 文字列ビルダー

StringBuilder は、Stringを構築するためのヘルパークラスです。 StringBuilder was introduced in Java 1.5 as a replacement for StringBuffer.

ループ内に巨大な文字列を作成するのに適しています。

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. 文字列ライター

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

The println function automatically adds new lines:

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. グアバジョイナー

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 has a Joiner class that is able to build multiline strings:

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

9. Loading From a File

Javaは、ファイルをそのまま読み取ります。 This means that if we have a multiline string in a text file, we’ll have the same string when we read the file. 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. IDE機能の使用

Many modern IDEs support multiline copy/paste. EclipseとIntelliJIDEAはそのようなIDEの例です。 We can simply copy our multiline string and paste it inside two double quotes in these IDEs.

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. 結論

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

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

レビューされた他のすべてのメソッドは、Java15またはそれ以前のバージョンで使用できます。

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