Java 13 文本块方法
Java 12 引入了文本块来处理多行字符串,例如JSON/XML/HTML等,并向String类添加了处理文本块的新方法。这是一个预览功能。
stripIndent() - 从字符串的开头和结尾删除空格。translateEscapes() - 根据字符串语法转义字符序列。
formatted() - 类似于String format()方法,在文本块字符串中支持格式化。
示例
考虑以下示例 –
ApiTester.java
public class APITester { public static void main(String[] args) { String textBlockJSON = """ { "name" : "%s", "RollNO" : "%s" } """.formatted("Mahesh", "32"); System.out.println(textBlockJSON); } }编译和运行程序
$javac -Xlint:preview --enable-preview -source 13 APITester.java$java --enable-preview APITester
输出
{"Name" : "Mahesh","RollNO" : "32"}{ "name" : "Mahesh", "RollNO" : "32"}Contains: trueindexOf: 15Length: 45 