养生 装修 购物 美食 感冒 便秘 营销 加盟 小吃 火锅 管理 创业 搭配 减肥 培训 旅游

java8中nio通道(Channel)的基本使用

时间:2024-11-02 12:27:48

java8中nio通道(Channel)的原理与获取基本使用

工具/原料

java8

intellijidea

方法/步骤

1、利用通道完成文件的复遄咿湫幼制@Testpublicvoidtest4()throwsException{FileChannel足毂忍珩inChannel=FileChannel.open(Paths.get("1.jpg"),StandardOpenOption.READ);FileChanneloutChannel=FileChannel.open(Paths.get("2.jpg"),StandardOpenOption.WRITE,StandardOpenOption.READ,StandardOpenOption.CREATE_NEW);//inChannel.transferTo(0,inChannel.size(),outChannel);outChannel.transferFrom(inChannel,0,inChannel.size());inChannel.close();outChannel.close();}

java8中nio通道(Channel)的基本使用

2、使用直接缓冲区完成文件的复制(内存映射文件)@Testpublicvoidtest2猾诮沓靥()throwsException{FileChannelinCha荏鱿胫协nnel=FileChannel.open(Paths.get("1.jpg"),StandardOpenOption.READ);FileChanneloutChannel=FileChannel.open(Paths.get("2.jpg"),StandardOpenOption.WRITE,StandardOpenOption.CREATE_NEW);//内存映射文件MappedByteBufferinMappedBuff=inChannel.map(FileChannel.MapMode.READ_ONLY,0,inChannel.size());MappedByteBufferoutMappedBuff=outChannel.map(FileChannel.MapMode.READ_WRITE,0,inChannel.size());//直接对缓冲区进行数据的读写操作byte[]dst=newbyte[inMappedBuff.limit()];inMappedBuff.get(dst);outMappedBuff.put(dst);}

java8中nio通道(Channel)的基本使用

3、通道之间的数据传输@Testpublicvoidtest4()throwsException{FileChannelinChannel=FileChannel.open(Paths.get("1.jpg"),StandardOpenOption.READ);FileChanneloutChannel=FileChannel.open(Paths.get("2.jpg"),StandardOpenOption.WRITE,StandardOpenOption.READ,StandardOpenOption.CREATE_NEW);inChannel.transferTo(0,inChannel.size(),outChannel);}

java8中nio通道(Channel)的基本使用

4、通道之间的数据传输(直接缓冲区)@Testpublicvoidtest4()throwsException{FileChannelinChannel=FileChannel.open(Paths.get("1.jpg"),StandardOpenOption.READ);FileChanneloutChannel=FileChannel.open(Paths.get("2.jpg"),StandardOpenOption.WRITE,StandardOpenOption.READ,StandardOpenOption.CREATE_NEW);outChannel.transferFrom(inChannel,0,inChannel.size());}

java8中nio通道(Channel)的基本使用

5、关闭输入通道连接@Testpublicvoidtest4()throwsException{FileChannelinChannel=FileChannel.open(Paths.get("1.jpg"),StandardOpenOption.READ);FileChanneloutChannel=FileChannel.open(Paths.get("2.jpg"),StandardOpenOption.WRITE,StandardOpenOption.READ,StandardOpenOption.CREATE_NEW);outChannel.transferFrom(inChannel,0,inChannel.size());inChannel.close();}

java8中nio通道(Channel)的基本使用

6、关闭输出通道连接@Testpublicvoidtest4()throwsException{FileChannelinChannel=FileChannel.open(Paths.get("1.jpg"),StandardOpenOption.READ);FileChanneloutChannel=FileChannel.open(Paths.get("2.jpg"),StandardOpenOption.WRITE,StandardOpenOption.READ,StandardOpenOption.CREATE_NEW);outChannel.transferFrom(inChannel,0,inChannel.size());inChannel.close();outChannel.close();}

java8中nio通道(Channel)的基本使用

© 一点知识