// Java 11 引入了许多新特性,以下是其中一些特性的示例代码
// 1. String 类的新方法
public class StringExamples {
public static void main(String[] args) {
// isBlank() 方法检查字符串是否为空或仅包含空白字符
String str1 = " ";
System.out.println(str1.isBlank()); // 输出: true
// lines() 方法将字符串按行分割成流
String str2 = "Hello\nWorld";
str2.lines().forEach(System.out::println); // 输出: Hello World
// strip() 方法去除字符串两端的空白字符(类似 trim(),但更强大)
String str3 = " Hello World ";
System.out.println("'" + str3.strip() + "'"); // 输出: 'Hello World'
// repeat() 方法重复字符串指定次数
String str4 = "Java ";
System.out.println(str4.repeat(3)); // 输出: Java Java Java
}
}
// 2. 文件 API 的改进
import java.nio.file.Path;
import java.nio.file.Paths;
public class FileExamples {
public static void main(String[] args) {
// resolve() 和 relativize() 方法的改进
Path path1 = Paths.get("/home/user/docs/file.txt");
Path path2 = Paths.get("/home/user/docs/images/photo.png");
Path resolvedPath = path1.getParent().resolve("images").resolve("photo.png");
System.out.println(resolvedPath); // 输出: /home/user/docs/images/photo.png
Path relativePath = path1.getParent().relativize(path2);
System.out.println(relativePath); // 输出: images/photo.png
}
}
// 3. HTTP Client API (标准版)
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.net.URI;
public class HttpClientExample {
public static void main(String[] args) throws Exception {
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("https://jsonplaceholder.typicode.com/posts/1"))
.build();
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
System.out.println(response.body()); // 输出: JSON 响应内容
}
}
String 类添加了多个实用的方法,如 isBlank()、lines()、strip() 和 repeat()。这些方法使得处理字符串更加方便和高效。Path 类进行了改进,提供了更简洁的方式来处理路径操作,例如 resolve() 和 relativize()。上一篇:java按行读取文件内容
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站