当前位置:   article > 正文

Java LTS版本——Java 11新特性

java lts

​​​​​​​

今天来总结一下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连接。

同步用法

  1. import java.io.IOException;
  2. import java.net.URI;
  3. import java.net.http.HttpClient;
  4. import java.net.http.HttpRequest;
  5. import java.net.http.HttpResponse;
  6. import java.time.Duration;
  7. HttpClient httpClient = HttpClient.newBuilder()
  8. .connectTimeout(Duration.ofSeconds(10))
  9. .build();
  10. try
  11. {
  12. String urlEndpoint = "https://postman-echo.com/get";
  13. URI uri = URI.create(urlEndpoint + "?foo1=bar1&foo2=bar2");
  14. HttpRequest request = HttpRequest.newBuilder()
  15. .uri(uri)
  16. .build();
  17. HttpResponse<String> response = httpClient.send(request,
  18. HttpResponse.BodyHandlers.ofString());
  19. } catch (IOException | InterruptedException e) {
  20. throw new RuntimeException(e);
  21. }
  22. System.out.println("Status code: " + response.statusCode());
  23. System.out.println("Headers: " + response.headers().allValues("content-type"));
  24. 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运行源码文件。

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

 直接运行:

  1. $ java HelloWorld.java
  2. Hello World

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

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

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

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

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

5.Optional.isEmpty()

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

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

6.String API中新增的函数

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

  1. public class HelloWorld
  2. {
  3. public static void main(String[] args)
  4. {
  5. String str = "2".repeat(5);
  6. System.out.println(str); //222222
  7. }
  8. }

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

  1. public class HelloWorld
  2. {
  3. public static void main(String[] args)
  4. {
  5. "1".isBlank(); //false
  6. "".isBlank(); //true
  7. " ".isBlank(); //true
  8. }
  9. }

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

  1. public class HelloWorld
  2. {
  3. public static void main(String[] args)
  4. {
  5. " hi ".strip(); //"hi"
  6. " hi ".stripLeading(); //"hi "
  7. " hi ".stripTrailing(); //" hi"
  8. }
  9. }

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

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

参考:

JDK 11 Documentation - Home

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

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/article/detail/53824?site
推荐阅读
相关标签
  

闽ICP备14008679号