String API
package jdk11;
import org.junit.Test;
import java.util.stream.Stream;
public class SpringAPI {
/**
* 判空
*/
@Test
public void isBlank(){
String blank1 = " "; // 半角空格
String blank2 = " "; // 全角空格
String blank3 = " "; // TAB
System.out.println(blank1.isBlank()); // true
System.out.println(blank2.isBlank()); // true
System.out.println(blank3.isBlank()); // true
}
/**
* 分割获取字符串流
* 输出
* a
* b
* c
*/
@Test
public void lines(){
String line = "a\nb\nc";
Stream<String> lines = line.lines();
lines.forEach(System.out::println);
}
/**
* 重复字符串
*/
@Test
public void repeat(){
String repeat = "复制字符串";
String copyRepeat = repeat.repeat(3);
System.out.println(copyRepeat); // 复制字符串复制字符串复制字符串
}
/**
* 去除前后空白字符
* trim 只能去除半角空格,而 strip 是去除各种空白符
*/
@Test
public void strip(){
// 去除前后空白
String strip = " xxxx ";
System.out.println("==" + strip.trim() + "=="); // == xxxx ==
// 去除前后空白字符,如全角空格,TAB
System.out.println("==" + strip.strip() + "=="); // ==xxxx==
// 去前面空白字符,如全角空格,TAB
System.out.println("==" + strip.stripLeading() + "=="); // ==xxxx ==
// 去后面空白字符,如全角空格,TAB
System.out.println("==" + strip.stripTrailing() + "=="); // == xxxx==
}
}
File API
package jdk11;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
public class FileAPI {
public static void main(String[] args) throws IOException {
// 创建临时文件
Path path = Files.writeString(Files.createTempFile("test", ".txt"), "读写文件变得更加方便");
System.out.println(path);
// 读取文件
String s = Files.readString(path);
System.out.println(s); // 读写文件变得更加方便
}
}
HTTP Client
package jdk11;
import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
/**
* 支持 HTTP/1.1 , HTTP/2 , websockets
* @link {OpenJDK 官方文档 http://openjdk.java.net/groups/net/httpclient/recipes-incubating.html}
*/
public class HttpClientAPI {
public static void main(String[] args) throws IOException, InterruptedException {
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder()
.GET()
.uri(URI.create("https://www.baidu.com"))
// .header()
.build();
// 异步
client.sendAsync(request, HttpResponse.BodyHandlers.ofString())
.thenApply(HttpResponse::body)
.thenAccept(System.out::println)
.join();
// 同步
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
System.out.println(response.body());
}
}
Lambda 局部变量推断
package jdk11;
import java.util.HashMap;
/**
* 在 Java 10 中引入了 var 语法,可以自动推断变量类型
* 在 Java 11 中这个语法糖可以在 Lambda 表达式中使用
*/
public class LambdaVar {
public static void main(String[] args) {
var hashMap = new HashMap<String, Object>();
hashMap.put("name", "fly");
hashMap.put("age", 18);
// (var k,var v) 中,k 和 v 的类型要么都用 var
// 要么都不写,
// 要么都写正确的变量类型。而不能 var 和其他变量类型混用
hashMap.forEach((var k, var v) ->{
System.out.println(k + ":" + v);
});
}
}