Java 简明教程

Java - Text Blocks

Java 在 Java 15 中将 text blocks 作为一项标准功能,用于处理多行 strings (如 JSON / XML / HTML 等)。它是在 Java 13 中作为预览功能引入的。

Java made text blocks in Java 15 as a standard feature to handle multiline strings like JSON/XML/HTML etc. It was introduced in Java 13 as a preview feature.

  1. Text Block allows to write multiline strings easily without using \r\n.

  2. Text Block string have same methods as string (String class methods) like contains(), indexOf(), and length() functions.

引入文本块的主要目的是以最高效的方式声明多行字符串。在文本块之前,我们可以使用字符串连接、字符串生成器追加方法、字符串连接方法来声明多行字符串,但是这种方法非常繁琐。因为我们必须使用行终止符、分隔符等来标记新的一行。文本块提供了一个更好的替代方法来使用 """, 即 3 个双引号标记来定义多行字符串。

Purpose of introducing text block is mainly to declare multi-line strings most efficiently. Prior to text block, we can declare multi-line strings using string concatenation, string builder append method, string join method but that approach is quite messy. As we have to use line terminators, delimiters etc to mark a new line. Text block provides a better and alternate approach to define multiline string using a """, 3 double-quotes mark.

Text Block Syntax

text block 是对现有 String 对象的增强,它采用了特殊语法,其中字符串内容应以带有换行符的 "" 开头,并以 """ 结尾。""" 内的任何内容都会按原样使用。

A text block is an enhancement to existing String object with special syntax where string content should starts with """ with newline and ends with """. Any content within """ will be used as-is.

String textBlockJSON = """
   {
      "name" : "Mahesh",
      "RollNO" : "32"
   }
   """;

可以使用旧语法编写等效字符串,如下所示:

Equivalent String can be written using older syntax as shown below:

String stringJSON = "{\r\n"
         + "   \"Name\" : \"Mahesh\",\r\n"
         + "   \"RollNO\" : \"32\"\r\n"
         + "}";

Example of Java Text Block

在此示例中,我们使用文本块和字符串连接打印了 JSON 字符串。

In this example, we’ve printed the json string using text block as well as using string concatenation.

package com.tutorialspoint;

public class Tester {

   public static void main(String[] args) {
      String stringJSON = "{\r\n"
      + "   \"Name\" : \"Mahesh\",\r\n"
      + "   \"RollNO\" : \"32\"\r\n"
      + "}";

      System.out.println(stringJSON);

      String textBlockJSON = """
      {
         "name" : "Mahesh",
         "RollNO" : "32"
      }
      """;
      System.out.println(textBlockJSON);
   }
}

Output

让我们编译并运行上述程序,这将生成以下结果 −

Let us compile and run the above program, this will produce the following result −

{
   "Name" : "Mahesh",
   "RollNO" : "32"
}
{
   "name" : "Mahesh",
   "RollNO" : "32"
}

Text Block String Operations

文本块与 String 相同,可以使用 equals() method 或相等运算符进行比较。

Text block is same as String and can be compared using equals() method or equal operator.

// compare the content,
textBlockJSON.equals(stringJSON);

// compare the objects
textBlockJSON == stringJSON;

文本块支持所有字符串操作,例如 indexOf()、contains() 等。

Text block supports all string operations like indexOf(), contains() etc.

// check if text block contains a provided string or not
textBlockJSON.contains("Mahesh");

// get the length of string content
textBlockJSON.length()

Example: Text Block String Operations in Java

在此示例中,我们执行了各种字符串操作,并将文本块与等效字符串进行比较。

In this example, we’ve performed various string operations and compared text block with an equivalent string.

package com.tutorialspoint;

public class Tester {

   public static void main(String[] args) {
      String stringJSON = "Mahesh";

      String textBlockJSON = """
      Mahesh""";
      // compare the content
      System.out.println(textBlockJSON.equals(stringJSON));

      // compare the objects
      System.out.println(textBlockJSON == stringJSON);

      // text block supports all string operations
      System.out.println("Contains: " + textBlockJSON.contains("Mahesh"));
      System.out.println("indexOf: " + textBlockJSON.indexOf("Mahesh"));
      System.out.println("Length: " + textBlockJSON.length());
   }
}

让我们编译并运行上述程序,这将生成以下结果 −

Let us compile and run the above program, this will produce the following result −

true
true
Contains: true
indexOf: 0
Length: 6

Text Block Methods

  1. stripIndent() - removes incidental white spaces from the start and end of the string.

  2. translateEscapes() - translate the escape sequences as per the string syntax.

  3. formatted() - similar to String format() method to support formatting in text block strings.

Example

考虑以下示例 −

Consider the following example −

ApiTester.java

public class APITester {

   public static void main(String[] args) {
	  String textBlockJSON = """
         {
            "name" : "%s",
            "RollNO" : "%s"
         }
         """.formatted("Mahesh", "32");
      System.out.println(textBlockJSON);
   }
}
{
   "name" : "Mahesh",
   "RollNO" : "32"
}