记录一下不知道的一些新特性
public class Main {
public static void main(String[] args) throws IOException, InterruptedException {
//jdk15
//文本块
String html = """
<html>
<body>
<p>Hello, world</p>
</body>
</html>
""";
System.err.println(html);
//instanceof模式匹配
Object obj = "11111111";
if(obj instanceof String str){
System.out.println(str);
}
//Switch表达式
int day = 1;
switch (day) {
case 1 -> System.out.println(1);
case 2 -> System.out.println(2);
case 3 -> System.out.println(3);
case 4 -> System.out.println(4);
}
//记录类型(Record Type)
Point point = new Point(1,3);
System.out.println(point.x());
System.out.println(point.y());
//jdk11
//本地变量类型推断(Local Var)
Arrays.asList("Java", "Python", "Ruby")
.forEach((var s) -> {
System.out.println("Hello, " + s);
});
//字符串加强
/**
* // 判断字符串是否为空白
* " ".isBlank(); // true
* // 去除首尾空格
* " Javastack ".strip(); // "Javastack"
* // 去除尾部空格
* " Javastack ".stripTrailing(); // " Javastack"
* // 去除首部空格
* " Javastack ".stripLeading(); // "Javastack "
* // 复制字符串
* "Java".repeat(3);// "JavaJavaJava"
* // 行数统计
* "A\nB\nC".lines().count(); // 3
*/
//创建不可变的集合 (List/ Set/ Map)都添加了 of 和 copyOf 方法
var list = List.of("Java", "Python", "C");
var copy = List.copyOf(list);
System.out.println(list == copy); // true
//Stream 加强
//...
//HTTP
var request = HttpRequest.newBuilder()
.uri(URI.create("https://www.baidu.com"))
.GET()
.build();
var client = HttpClient.newHttpClient();
// 同步
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
System.out.println(response.body());
// 异步
client.sendAsync(request, HttpResponse.BodyHandlers.ofString())
.thenApply(HttpResponse::body)
.thenAccept(System.out::println);
//直接把String写入文件,或者把整个文件读出为一个String
Files.writeString(
Path.of("./", "tmp.txt"), // 路径
"hello, jdk11 files api", // 内容
StandardCharsets.UTF_8); // 编码
String s = Files.readString(
Paths.get("./tmp.txt"), // 路径
StandardCharsets.UTF_8); // 编码
System.out.println(s);
}
}
record Point(Integer x,Integer y) {
}