首页 > 编程语言 >无涯教程-Java NIO - AsynchronousFileChannel

无涯教程-Java NIO - AsynchronousFileChannel

时间:2023-12-29 13:31:47浏览次数:45  
标签:Java nio java 无涯 System AsynchronousFileChannel file import out

无涯教程知道Java NIO支持并发和多线程,这允许同时处理不同的通道,因此Java NIO包中负责此操作的API是AsynchronousFileChannel。

AsynchronousFileChannel与NIO的FileChannel相似,不同之处在于此通道使文件操作能够异步执行。

在异步中,线程将请求传递给操作系统的内核以完成请求,而线程继续处理另一个作业。一旦内核的作业完成,它将向线程发出信号,然后线程确认信号并中断当前作业并处理I/O工作根据需要。

AsynchronousFileChannel示例

以下示例显示了如何使用Future对象以及如何异步执行任务。

package com.java.nio;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousFileChannel;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;

public class FutureObject {
   public static void main(String[] args) throws Exception {
      readFile();
   }
   private static void readFile() throws IOException, InterruptedException, ExecutionException {
      String filePath = "D:fileCopy.txt";
      printFileContents(filePath);
      Path path = Paths.get(filePath);		
      AsynchronousFileChannel channel =AsynchronousFileChannel.open(path, StandardOpenOption.READ);
      ByteBuffer buffer = ByteBuffer.allocate(400);
      Future<Integer> result = channel.read(buffer, 0); //position=0
      while (! result.isDone()) {
         System.out.println("Task of reading file is in progress asynchronously.");
      }
      System.out.println("Reading done: " + result.isDone());
      System.out.println("Bytes read from file: " + result.get()); 
      buffer.flip();
      System.out.print("Buffer contents: ");
      while (buffer.hasRemaining()) {
         System.out.print((char) buffer.get());                
      }
      System.out.println(" ");
      buffer.clear();
      channel.close();
   }
   private static void printFileContents(String path) throws IOException {
      FileReader fr = new FileReader(path);
      BufferedReader br = new BufferedReader(fr);
      String textRead = br.readLine();
      System.out.println("File contents: ");
      while (textRead != null) {
         System.out.println("     " + textRead);
         textRead = br.readLine();
      }
   fr.close();
   br.close();
   }
}

运行上面代码输出

File contents: 
   To be or not to be?
   Task of reading file is in progress asynchronously.
   Task of reading file is in progress asynchronously.
   Reading done: true
   Bytes read from file: 19
   Buffer contents: To be or not to be? 

CompletionHandler示例

下面的示例演示如何使用CompletionHandler异步执行任务。

package com.java.nio;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousFileChannel;
import java.nio.channels.CompletionHandler;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;

public class CompletionHandlerDemo {
   public static void main (String [] args) throws Exception {
      writeFile();
   }
   private static void writeFile() throws IOException {
      String input = "Content to be written to the file.";
      System.out.println("Input string: " + input);
      byte [] byteArray = input.getBytes();
      ByteBuffer buffer = ByteBuffer.wrap(byteArray);
      Path path = Paths.get("D:fileCopy.txt");
      AsynchronousFileChannel channel = AsynchronousFileChannel.open(path, StandardOpenOption.WRITE);
      CompletionHandler handler = new CompletionHandler() {
         @Override
         public void completed(Object result,Object attachment) {
            System.out.println(attachment + " completed and " + result + " bytes are written.");
         }
         @Override
         public void failed(Throwable exc,Object attachment) {
            System.out.println(attachment + " failed with exception:");
            exc.printStackTrace();
         }
      };
      channel.write(buffer, 0, "Async Task", handler);
      channel.close();
      printFileContents(path.toString());
   }
   private static void printFileContents(String path) throws IOException {
      FileReader fr = new FileReader(path);
      BufferedReader br = new BufferedReader(fr);
      String textRead = br.readLine();
      System.out.println("File contents: ");
      while (textRead != null) {
         System.out.println("     " + textRead);
         textRead = br.readLine();
      }
      fr.close();
      br.close();
   }
}

运行上面代码输出

Input string: Content to be written to the file.
Async Task completed and 34 bytes are written.
File contents: 
Content to be written to the file.

参考链接

https://www.learnfk.com/java-nio/java-nio-asynchronous-filechannel.html

标签:Java,nio,java,无涯,System,AsynchronousFileChannel,file,import,out
From: https://blog.51cto.com/u_14033984/9027111

相关文章

  • Java反射,看完就会用
    什么是反射在说反射概念之前,我们先说另外2个概念:编译期和运行期。编译期:编译期是源代码从文本形式转换为字节码的过程,这发生在Java代码被JVM执行之前。在编译期,编译器对源代码进行语法检查、类型检查、变量名解析等操作,确保代码符合Java的语法规则,并将其编译成字节码(.class文......
  • 无涯教程-Java NIO - Path(路径)
    顾名思义,Path是实体(如文件或目录)在文件系统中的特定位置,以便人们可以在该特定位置搜索和访问它。通常,一个实体的路径可以是两种,一种是绝对路径,另一种是相对路径,为了获得Path的,无涯教程可以使用java.nio.file.Paths类get()的静态方法。如上所述,绝对路径是通过传递根元素和定......
  • Java第二十课_File
    1.FileFile常用函数publicstaticvoidmain(String[]args)throwsIOException{//相对路径:IO流默认目录:当前项目工程开始自己算//绝对路径:带盘符的路径://网络路径:https://img2.baidu.com/it/u=3164322677,862193441&fm=2......
  • linux下java调用netcore程序
    代码备份仅供参考自述文件#JavaCallCSharpJavacallC#libbuildwith.NETCORE2.0viaC++aswraperThecodeisbasedon[examplefromcoreCLR](https://github.com/dotnet/coreclr/tree/master/src/coreclr/hosts/unixcoreruncommon)JavausingJNItocallC++......
  • Linux下netcore调用java代码
    代码备份,仅供参考自述文件#CSharpCallJavaC#invokeJavaviaC++asawraper.C#invokeC++viaP/invoke.C++startsaJVMtoruntheJavacode.C#codeshouldbecompiledin.NETcore2.0YoushouldedittheMakefiletosetthePathofJavaSDKexpor......
  • 关于IDEA报 java: 无法访问java.lang.Record 找不到java.lang.Record的类文件
    IDEA一直报java:无法访问java.lang.Record  找不到java.lang.Record的类文件,但是我已经把所有的java配置改成了17。最后发现是pom文件中org.apache.maven.plugins配置没有改。属性修改如下:<configuration><compilerVersion>1.8</compilerVersion>-......
  • 【随手记录】Apache-JMeter部署银河麒麟报错: jmeter module java.desktop does not "o
    操作系统:Linux0012.novalocal4.19.90-17.ky10.aarch64#1SMPSunJun2814:27:40CST2020aarch64aarch64aarch64GNU/LinuxJDK版本:java17.0.82023-07-18LTSJava(TM)SERuntimeEnvironment(build17.0.8+9-LTS-211)JavaHotSpot(TM)64-BitServerVM(build......
  • 「Java开发指南」如何用MyEclipse搭建JSF/Primefaces和Spring(二)
    本教程将引导大家完成为JavaServerFaces(JSF)生成软件组件的过程,在本文中您将学习到如何:从数据库表到现有项目搭建配置支持JSF2.0的服务器部署搭建的应用程序在上文中,我们介绍了如何创建一个Web项目、从数据库表搭建及配置服务器等,本文将继续介绍如何部署应用程序!更多MyE......
  • The JAVA_HOME environment variable is not defined correctly,解决
    k8s集成jenkins,在进行子工程mvncleaninstall过程中报截图中错误,经过排除是之前在系统管理->系统配置中,添加的JAVA_HOME环境变量不对,可能目前我使用的jenkins是通过k8sPod生成的,并不是直接在主机上安装的,所以此处填的JAVA_HOMEjenkins识别不到,所以报错.取消后不再报错.......
  • Java中的非对称加密算法原理与实现
    引言在当今的信息时代,数据安全已经成为了一个至关重要的问题。加密技术作为保障信息安全的重要手段,受到了广泛的应用和关注。其中,非对称加密算法因其高效、安全的特点,在众多加密方法中独树一帜。本篇文章将详细介绍Java中的非对称加密算法原理及其实现方式。一、非对称加密算法概述......