Java 17 引入了 Text Blocks(文本块) 特性,这是 Java 语言中一种新的字符串表示方式,旨在简化多行字符串的创建和处理。它通过减少转义字符的需求,使代码更加简洁、易读。
Text Blocks 的基本用法
Text Blocks 使用三个双引号 """
来界定字符串内容。与普通字符串不同,Text Blocks 可以跨多行,并且保留字符串中的换行符和缩进。
示例:
ini
String json = """
{
"name": "Alice",
"age": 25,
"city": "New York"
}
""";
System.out.println(json);
输出:
json
{
"name": "Alice",
"age": 25,
"city": "New York"
}
Text Blocks 的特点
- 自动处理换行符 : Text Blocks 会保留字符串中的换行符,无需手动插入
\n
。
ini
String text = """
Line 1
Line 2
Line 3
""";
System.out.println(text);
输出:
scss
Line 1
Line 2
Line 3
- 减少转义字符 : 在普通字符串中,双引号需要使用反斜杠
\
转义,而 Text Blocks 不需要。
ini
// 普通字符串
String html = "<html>\n" +
" <body>\n" +
" <p>Hello, World!</p>\n" +
" </body>\n" +
"</html>";
// 使用 Text Blocks
String htmlBlock = """
<html>
<body>
<p>Hello, World!</p>
</body>
</html>
""";
- 自动去除缩进: Text Blocks 会根据最左边非空字符的位置自动调整缩进。这使得代码格式化更灵活。
ini
String query = """
SELECT *
FROM users
WHERE id = 1
""";
System.out.println(query);
输出:
sql
SELECT *
FROM users
WHERE id = 1
- 支持表达式嵌入 : 和普通字符串一样,Text Blocks 支持嵌入表达式,使用
${}
格式。
ini
int age = 25;
String message = """
Hello, my name is Alice.
I am %d years old.
""".formatted(age);
System.out.println(message);
输出:
erlang
Hello, my name is Alice.
I am 25 years old.
注意事项
- 结束符必须单独一行 : 结束的三引号
"""
必须独占一行,不能与内容在同一行。错误示例:
ini
String text = """
This is a text block""";
正确示例:
ini
String text = """
This is a text block
""";
- 保留换行符 : 如果你希望去掉某行的换行符,可以在该行末尾添加反斜杠
\
。
ini
String text = """
Line 1 \
Line 2
""";
System.out.println(text);
输出:
scss
Line 1 Line 2
- 缩进规则 : Text Blocks 会根据最左边非空字符的位置自动调整缩进,但你可以通过工具类(如
String.stripIndent()
或String.translateEscapes()
)手动控制缩进。
适用场景
- JSON 和 XML 数据:Text Blocks 非常适合用来定义 JSON、XML 等多行数据格式。
- SQL 查询:可以轻松编写复杂的 SQL 查询语句。
- HTML 和 CSS:用于生成 HTML 页面或 CSS 样式表。
- 多行日志消息:在日志记录中生成格式化的多行消息。
总结
Text Blocks 是 Java 17 中一个非常实用的特性,特别适用于处理多行字符串。它减少了转义字符的使用,提升了代码的可读性和维护性。