广州北大青鸟计算机职业培训学校
互联网技术培训、软件技术培训、大数据培训、云计算培训、数据分析培训信息网
当前位置:网站首页 > 软件教程 > Java技术 > 正文

惠州分享Java异步实例_北大青鸟IT学校

作者:邓华发布时间:2021-04-14分类:Java技术浏览:889


导读:上一篇文章惠州北大青鸟老师给大家分享了Java异步I/O相关的知识,为了让大家更好的理解什么是Java异步,下面老是个大家分享Java异步实例。

上一篇文章惠州北大青鸟老师给大家分享了Java异步I/O相关的知识,为了让大家更好的理解什么是Java异步,下面老是个大家分享Java异步实例。

实例一 

以下代码演示了如何使用CompletionHandler对象来处理从文件进行异步读取的结果。

import static java.nio.file.StandardOpenOption.READ;import java.io.IOException;import java.nio.ByteBuffer;import java.nio.channels.AsynchronousFileChannel;import java.nio.channels.CompletionHandler;import java.nio.charset.Charset;import java.nio.file.Path;import java.nio.file.Paths;public class Main {  public static void main(String[] args) throws Exception{
   Path path = Paths.get("test.txt");
   AsynchronousFileChannel afc = AsynchronousFileChannel.open(path, READ);
   ReadHandler handler = new ReadHandler();    int fileSize = (int) afc.size();
   ByteBuffer dataBuffer = ByteBuffer.allocate(fileSize);

   Attachment attach = new Attachment();
   attach.asyncChannel = afc;
   attach.buffer = dataBuffer;
   attach.path = path;

   afc.read(dataBuffer, 0, attach, handler);

   System.out.println("Sleeping for 5  seconds...");
   Thread.sleep(5000);
 }
}class Attachment {  public Path path;  public ByteBuffer buffer;  public AsynchronousFileChannel asyncChannel;
}class ReadHandler implements CompletionHandler<Integer, Attachment> {
 @Override  public void completed(Integer result, Attachment attach) {
   System.out.format("%s bytes read   from  %s%n", result, attach.path);
   System.out.format("Read data is:%n");    byte[] byteData = attach.buffer.array();
   Charset cs = Charset.forName("UTF-8");
   String data = new String(byteData, cs);
   System.out.println(data);    try {      // Close the channel      attach.asyncChannel.close();
   } catch (IOException e) {
     e.printStackTrace();
   }
 }

 @Override  public void failed(Throwable e, Attachment attach) {
   System.out.format("Read operation  on  %s  file failed."
       + "The  error is: %s%n", attach.path, e.getMessage());    try {      // Close the channel      attach.asyncChannel.close();
   } catch (IOException e1) {
     e1.printStackTrace();
   }
 }
}

上面的代码生成以下结果。

Sleeping for 5 seconds...

22 bytes read from test.txt

Read data is:

test

test

test

test

实例二

以下代码显示了如何使用Future对象来处理从文件进行异步读取的结果。它使用等待方法(Future.get()方法调用)等待异步文件I/O完成。

import static java.nio.file.StandardOpenOption.READ;import java.io.IOException;import java.nio.ByteBuffer;import java.nio.channels.AsynchronousFileChannel;import java.nio.charset.Charset;import java.nio.file.Path;import java.nio.file.Paths;import java.util.concurrent.ExecutionException;import java.util.concurrent.Future;public class Main {  public static void main(String[] args) throws Exception {
   Path path = Paths.get("test.txt");    try (AsynchronousFileChannel afc = AsynchronousFileChannel.open(path, READ)) {      int fileSize = (int) afc.size();
     ByteBuffer dataBuffer = ByteBuffer.allocate(fileSize);

     Future<Integer> result = afc.read(dataBuffer, 0);      int readBytes = result.get();

     System.out.format("%s bytes read   from  %s%n", readBytes, path);
     System.out.format("Read data is:%n");      byte[] byteData = dataBuffer.array();
     Charset cs = Charset.forName("UTF-8");
     String data = new String(byteData, cs);

     System.out.println(data);
   } catch (IOException ex) {
     ex.printStackTrace();
   }
 }
}

上面的代码生成以下结果。

13 bytes read from test.txt

Read data is:

test

test2

实例三

以下代码演示了如何使用Future对象来处理对文件的异步写入的结果。

import static java.nio.file.StandardOpenOption.CREATE;import static java.nio.file.StandardOpenOption.WRITE;import java.io.IOException;import java.nio.ByteBuffer;import java.nio.channels.AsynchronousFileChannel;import java.nio.charset.Charset;import java.nio.file.Path;import java.nio.file.Paths;import java.util.concurrent.Future;public class Main {  public static ByteBuffer getDataBuffer() {
   String lineSeparator = System.getProperty("line.separator");

   StringBuilder sb = new StringBuilder();
   sb.append("test");
   sb.append(lineSeparator);

   String str = sb.toString();
   Charset cs = Charset.forName("UTF-8");
   ByteBuffer bb = ByteBuffer.wrap(str.getBytes(cs));    return bb;
 }  public static void main(String[] args) throws Exception {
   Path path = Paths.get("test.txt");    try (AsynchronousFileChannel afc = AsynchronousFileChannel.open(path,
       WRITE, CREATE)) {
     ByteBuffer dataBuffer = getDataBuffer();
     Future<Integer> result = afc.write(dataBuffer, 0);      while (!result.isDone()) {
       System.out.println("Sleeping for 2  seconds...");
       Thread.sleep(2000);
     }      int writtenBytes = result.get();
     System.out.format("%s bytes written  to  %s%n", writtenBytes,
         path.toAbsolutePath());

   } catch (IOException e) {
     e.printStackTrace();
   }
 }
}

上面的代码生成以下结果。

Sleeping for 2 seconds...

6 bytes written to E:\Java_Dev\WEB\release\java2sIDE\generated\a\test.txt

想知道更多关于Java的资讯,联系在线客服,或者来惠州北大青鸟新方舟校区了解了解。

java3.png

Java

标签:惠州计算机JAVA软件开发惠州计算机Java软件开发惠州计算机JAVA培训惠州计算机JAVA软件开发学校惠州计算机Java软件开发培训JAVAJava软件开发北大青鸟IT计算机学校北大青鸟IT软件学校北大青鸟IT学校


Java技术排行
标签列表
网站分类
文章归档
最近发表