Java LTS版本——Java 11新特性

​​​​​​​

今天来总结一下Java11版本中主要的新特性。供大家学习参考。

目录

1.HTTP Client API

同步用法

异步用法:需要用到SendSync方法

2.直接运行单个Java文件

3.新增了一个集合到数组之间的方法

4.Files.readString()和Files.writeString()

5.Optional.isEmpty()

6.String API中新增的函数


1.HTTP Client API

Java11之前要处理HTTP的连接,需要用到HttpUrlConnection,会导致非常的复杂,而且需要封装不同参数的很多处理方法。可能会使用到第三方的依赖库。比如:OkHttp等。

从Java11开始,就可以不用使用第三方的依赖库来处理HTTP连接。

同步用法

import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.Duration;
 
HttpClient httpClient = HttpClient.newBuilder()
                .connectTimeout(Duration.ofSeconds(10))
                .build();                                  
 
try
{
    String urlEndpoint = "https://postman-echo.com/get";
    URI uri = URI.create(urlEndpoint + "?foo1=bar1&foo2=bar2");
    HttpRequest request = HttpRequest.newBuilder()
                        .uri(uri)
                        .build();                              
    HttpResponse<String> response = httpClient.send(request,
                          HttpResponse.BodyHandlers.ofString()); 
} catch (IOException | InterruptedException e) {
    throw new RuntimeException(e);
}
 
System.out.println("Status code: " + response.statusCode());                            
System.out.println("Headers: " + response.headers().allValues("content-type"));               
System.out.println("Body: " + response.body()); 

异步用法:需要用到SendSync方法

import java.io.IOException;

import java.net.URI;

import java.net.http.HttpClient;

import java.net.http.HttpRequest;

import java.net.http.HttpResponse;

import java.time.Duration;

import java.util.List;

import java.util.concurrent.CompletableFuture;

import java.util.stream.Stream;

import static java.util.stream.Collectors.toList;

final List<URI> uris = Stream.of(

                "https://www.google.com/",

                "https://www.github.com/",

                "https://www.yahoo.com/"

                ).map(URI::create).collect(toList());     

HttpClient httpClient = 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(futures).join();          

private CompletableFuture<Void> verifyUri(HttpClient httpClient,

                                          URI uri)

{

    HttpRequest request = HttpRequest.newBuilder()

                        .timeout(Duration.ofSeconds(5))

                        .uri(uri)

                        .build();

    return httpClient.sendAsync(request,HttpResponse.BodyHandlers.ofString())

                  .thenApply(HttpResponse::statusCode)

                  .thenApply(statusCode -> statusCode == 200)

                  .exceptionally(ex -> false)

                  .thenAccept(valid ->

                  {

                      if (valid) {

                          System.out.println("[SUCCESS] Verified " + uri);

                      } else {

                          System.out.println("[FAILURE] Could not " + "verify " + uri);

                      }

                  });                                   

}

2.直接运行单个Java文件

Java11之前的版本,如果要运行单个Java文件,首先通过Javac 编译成字节码文件,然后再通过Java命令运行。现在可以直接通过java HelloWorld.java运行源码文件。

public class HelloWorld {
    public static void main(String[] args) {
        System.out.println("Hello World!");
    }
}

 直接运行:

$  java HelloWorld.java

Hello World

3.新增了一个集合到数组之间的方法

public class HelloWorld 
{
    public static void main(String[] args) 
    {
      List<String> names = new ArrayList<>();
      names.add("alex");
      names.add("brian");
      names.add("charles");
 
      String[] namesArr1 = names.toArray(new String[names.size()]);   //Java 11之前的做法
 
      String[] namesArr2 = names.toArray(String[]::new);          //从Java 11 开始
    }
}

4.Files.readString()和Files.writeString()

使用File.readString和Files.writeString方法能帮助我们减少编写重复代码。方便文件的读写。

public class HelloWorld 
{
    public static void main(String[] args) 
    {
      //Read file as string
      URI txtFileUri = getClass().getClassLoader().getResource("helloworld.txt").toURI();
 
      String content = Files.readString(Path.of(txtFileUri),Charset.defaultCharset());
 
      //Write string to file
      Path tmpFilePath = Path.of(File.createTempFile("tempFile", ".tmp").toURI());
 
      Path returnedFilePath = Files.writeString(tmpFilePath,"Hello World!", 
                    Charset.defaultCharset(), StandardOpenOption.WRITE);
    }
}

5.Optional.isEmpty()

Optional新增了isEmpty()这个方法,和之前的isPresent()是相反的。isPresent()用来判断值是否存在。isEmpty用来判断值是否为空。

public class HelloWorld 
{
    public static void main(String[] args) 
    {
      String currentTime = null;
 
      assertTrue(!Optional.ofNullable(currentTime).isPresent());  //判断值是否存在
      assertTrue(Optional.ofNullable(currentTime).isEmpty());   //判断值是否存在的正向写法
 
      currentTime = "12:00 PM";
 
      assertFalse(!Optional.ofNullable(currentTime).isPresent()); /判断值是否存在
      assertFalse(Optional.ofNullable(currentTime).isEmpty());  //判断值是否存在的正向写法
    }
}

6.String API中新增的函数

String.repeat(Integer n):函数返回当前字符串重复n次之后的字符串

public class HelloWorld 
{
    public static void main(String[] args) 
    {
    	String str = "2".repeat(5);

        System.out.println(str);	//222222
    }
}

 String.isBlank():判断字符串是否为空或者只包含空格

public class HelloWorld 
{
    public static void main(String[] args) 
    {
    	"1".isBlank();	//false

        "".isBlank();	//true

        "    ".isBlank();	//true
    }
}

String.strip():用来删除字符串开头或者结尾的空格,还包括两个函数:String.stripLeading()和String.stripTrailing()。分别用来删除开头和结尾的空格。

public class HelloWorld 
{
    public static void main(String[] args) 
    {
      "   hi  ".strip();  //"hi"
 
       "   hi  ".stripLeading();  //"hi   "
 
       "   hi  ".stripTrailing(); //"   hi"
    }
}

 String.lines():用来把多行文字转换成Stream(Java 8引入)

public class HelloWorld 
{
    public static void main(String[] args) 
    {
      String testString = "hello\nworld\nis\nexecuted";
 
      List<String> lines = new ArrayList<>();
 
      testString.lines().forEach(line -> lines.add(line));
 
      assertEquals(List.of("hello", "world", "is", "executed"), lines);
    }
}

参考:

JDK 11 Documentation - Home

有什么问题,欢迎大家私信交流。

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

83Dillon

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值