大家好,我是大洋。本文向您介绍了Java11的新特性,并提供了一些代码示例。本文主要内容HTTP客户端API无需编译StringAPI即可启动单文件程序更新Collection.toArrayFiles.readString()和Files.writeString()Optional.isEmpty()Java11(2018年9月发布)包含许多重要且有用的内容更新。让我们来看看它为开发者和架构师带来的新特性和改进。1.HTTPClientAPIJava长期以来一直使用HttpURLConnection进行HTTP通信。但随着时间的推移,要求变得越来越复杂,应用程序也越来越苛刻。在Java11之前,开发人员不得不求助于功能丰富的库,如ApacheHttpComponents或OkHttp等。我们看到Java9版本包含一个HttpClient实现作为实验性功能。它随着时间的推移而发展,现在是Java11的最终功能。现在Java应用程序可以通过HTTP进行通信而无需任何外部依赖。1.1如何使用HttpClientjava.net.http模块和一个典型的HTTP交互如下:创建一个HttpClient实例,并根据需要进行配置。创建一个HttpRequest实例并用信息填充它。将请求传递给客户端,执行请求并检索HttpResponse的实例。处理HttpResponse中包含的信息。HTTPAPI可以处理同步和异步通信。让我们看一个简单的例子。1.2同步请求示例注意http客户端API如何使用构建器模式来创建复杂对象。packagecn.dayangshuo.http;importjava.io.IOException;importjava.net.URI;importjava.net.http.HttpClient;importjava.net.http.HttpRequest;importjava.net.http.HttpResponse;importjava.time.Duration;/***@authorDAYANG*/publicclassHttpClientTest{publicstaticvoidmain(String[]args){HttpClienthttpClient=HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(10)).build();try{StringurlEndpoint="https://www.baidu.com/s";URIuri=URI.create(urlEndpoint+"?wd=java11");HttpRequest请求=HttpRequest.newBuilder().uri(uri).build();HttpResponseresponse=httpClient.send(request,HttpResponse.BodyHandlers.ofString());System.out.println("状态码:"+response.statusCode());System.out.println("标题:&》;+response.headers().allValues("内容类型"));System.out.println("正文:"+response.body());}catch(IOException|InterruptedExceptione){thrownewRuntimeException(e);}}}1.3异步请求示例如果我们不想等待响应,异步通信很有用。我们提供在响应可用时执行的回调处理程序。请注意使用sendAsync()方法发送异步请求。packagecn.dayangshuo.http;importjava.net.URI;importjava.net.http.HttpClient;importjava.net.http.HttpRequest;importjava.net.http.HttpResponse;importjava.time.Duration;importjava.util.List;importjava.util.concurrent.CompletableFuture;importjava.util.stream.Stream;importstaticjava.util.stream.Collectors.toList;/***@authorDAYANG*/publicclassHttpClientTest{publicstaticvoidmain(String[]args){finalListuris=Stream.of("https://www.baidu.com/","https://www.zhihu.com/people/da-yang-12-48","https://dayangshuo.cn").map(URI::create).collect(toList());HttpClienthttpClient=HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(10)).followRedirects(HttpClient.Redirect.ALWAYS).build();//回调设置CompletableFuture[]futures=uris.stream().map(uri->verifyUri(httpClient,uri)).toArray(CompletableFuture[]::new);CompletableFuture.allOf(期货).join();}privatestaticCompletableFutureverifyUri(HttpClienthttpClient,URIuri){HttpRequestrequest=HttpRequest.newBuilder().timeout(Duration.ofSeconds(5)).uri(uri).build();返回httpClient.sendAsync(request,HttpResponse.BodyHandlers.ofString()).thenApply(HttpResponse::statusCode).thenApply(statusCode->statusCode==200).exceptionally(ex->false).thenAccept(valid->{如果(有效){System.out.println("[SUCCESS]已验证"+uri);}else{System.out.println("[FAILURE]无法"+"验证"+uri);}});}}2.不编译启动单文件程序传统上,对于每一个我们要执行的程序,我们都需要先编译它。对于用于测试目的的小程序,这似乎是一个不必要的冗长过程。Java11改变了这一点,现在我们可以执行包含在单个文件中的Java源代码,而无需先编译它。写一个简单的HelloWorld.javapublicclassHelloWorld{publicstaticvoidmain(String[]args){System.out.println("HelloWorld!");}}要执行上面的类,直接用java命令运行://console$javaHelloWorld.javaHelloWorld!请注意,除了使用java.base模块模块化之外,该程序不能使用任何外部依赖项。而且程序只能是单文件程序。3.StringAPI更新3.1String.repeat(Integer)这个方法只是重复一个字符串n次。它返回一个字符串,其值是给定字符串重复N次的串联。如果此字符串为空或计数为零,则返回空字符串。publicclassHelloWorld{publicstaticvoidmain(String[]args){Stringstr="1".repeat(5);//打印出来:11111System.out.println(str);}}3.2.String.isBlank()此方法指示字符串是空的还是仅包含空格。之前,我们一直在使用Apache的StringUtils.java.publicclassHelloWorld{publicstaticvoidmain(String[]args){"1".isBlank();//假"".isBlank();//真"".isBlank();//真}}3.3。String.strip()此方法负责删除前导和尾随空格。我们可以使用String.stripLeading()只删除前导字符,使用String.stripTrailing()只删除尾随字符。publicclassHelloWorld{publicstaticvoidmain(String[]args){“hi”.strip();//“嗨”“嗨”.stripLeading();//“嗨”“嗨”.stripTrailing();//“嗨”}}3.4。String.lines()此方法有助于将多行文本作为流处理。公共类HelloWorld{publicstaticvoidmain(String[]args){StringtestString="hello\nworld\nis\nexecuted";列表<字符串>行=新的ArrayList<>();testString.lines().forEach(line->lines.add(line));assertEquals(List.of("hello","world","is","executed"),lines);}}4。Collection.toArray在Java11之前,将集合转换为数组并非易事。Java11使转换变得更加容易。publicclassHelloWorld{publicstaticvoidmain(String[]args){Listnames=newArrayList<>();names.add("亚历克斯");names.add("布莱恩");names.add(“查尔斯”);String[]namesArr1=names.toArray(newString[names.size()]);//Java11之前String[]namesArr2=names.toArray(String[]::new);//Java11}}5.Files.readString()和Files.writeString()通过使用这些重载方法,Java11旨在减少大量样板代码,从而更轻松地读写文件。publicclassHelloWorld{publicstaticvoidmain(String[]args){//读取文件内容作为字符串URItxtFileUri=getClass().getClassLoader().getResource("helloworld.txt").toURI();字符串内容=Files.readString(Path.of(txtFileUri),Charset.defaultCharset());//将字符串写入文件PathtmpFilePath=Path.of(File.createTempFile("tempFile",".tmp").toURI());路径returnedFilePath=Files.writeString(tmpFilePath,"HelloWorld!",Charset.defaultCharset(),StandardOpenOption.WRITE);}}6.Optional.isEmpty()Optional是一个容器对象,它可能包含也可能不包含非空值。如果不存在任何值,则该对象被认为是空的。如果值存在,isPresent()方法返回true,否则返回false。isEmpty()方法与isPresent()方法相反,如果值存在则返回false,否则返回true。所以我们无论如何都不写负面条件。根据需要使用这些方法之一。publicclassHelloWorld{publicstaticvoidmain(String[]args){StringcurrentTime=null;assertTrue(!Optional.ofNullable(currentTime).isPresent());assertTrue(Optional.ofNullable(currentTime).isEmpty());当前时间="12:00PM";assertFalse(!Optional.ofNullable(currentTime).isPresent());assertFalse(Optional.ofNullable(currentTime).isEmpty());}}