java的NIO的学习教程,网上一大把,本文只是学习的笔记。
本文参考和复制如下内容:
https://www.cnblogs.com/mikechenshare/p/16587635.html
https://blog.csdn.net/K_520_W/article/details/123454627
https://www.zhihu.com/question/29005375
一、NIO简介
NIO 同步非阻塞IO,多路复用,其目的是提高速度。主要的使用场景是在网络IO。对于传统的文件IO,优势不明显。
NIO是面向缓冲区(Buffer)的。
可简单认为:
IO是面向流的处理,NIO是面向块(缓冲区)的处理
面向流的I/O 系统一次一个字节地处理数据。
一个面向块(缓冲区)的I/O系统以块的形式处理数据。
NIO主要有三个核心部分组成:
buffer缓冲区
Channel管道
Selector选择器
用实际的实例来学习一下把!
1、NIO复制文件和传统IO复制文件的demo
import java.io.*; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; public class SimpleFileTransferTest { /** * 普通的io文件流 * @param source * @param des * @return * @throws IOException */ private long transferFile(File source, File des) throws IOException { long startTime = System.currentTimeMillis(); if (!des.exists()) des.createNewFile(); BufferedInputStream bis = new BufferedInputStream(new FileInputStream(source)); BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(des)); //将数据源读到的内容写入目的地--使用数组 byte[] bytes = new byte[1024 * 1024]; int len; while ((len = bis.read(bytes)) != -1) { bos.write(bytes, 0, len); } long endTime = System.currentTimeMillis(); return endTime - startTime; } /** * nio操作文件流 * @param source * @param des * @return * @throws IOException */ private long transferFileWithNIO(File source, File des) throws IOException { long startTime = System.currentTimeMillis(); if (!des.exists()) des.createNewFile(); RandomAccessFile read = new RandomAccessFile(source, "rw"); RandomAccessFile write = new RandomAccessFile(des, "rw"); FileChannel readChannel = read.getChannel(); FileChannel writeChannel = write.getChannel(); ByteBuffer byteBuffer = ByteBuffer.allocate(1024 * 1024);//1M缓冲区 while (readChannel.read(byteBuffer) > 0) { byteBuffer.flip(); writeChannel.write(byteBuffer); byteBuffer.clear(); } writeChannel.close(); readChannel.close(); long endTime = System.currentTimeMillis(); return endTime - startTime; } public static void main(String[] args) throws IOException { SimpleFileTransferTest simpleFileTransferTest = new SimpleFileTransferTest(); File sourse = new File("E:\\VSWork\\spring-plugin-cli-master.rar"); File des = new File("E:\\VSWork\\spring-plugin-cli-master-io.rar"); File nio = new File("E:\\VSWork\\spring-plugin-cli-master-nio.rar"); long time = simpleFileTransferTest.transferFile(sourse, des); System.out.println(time + ":普通字节流时间"); long timeNio = simpleFileTransferTest.transferFileWithNIO(sourse, nio); System.out.println(timeNio + ":NIO时间"); } }View Code
标签:NIO,des,笔记,学习,source,long,File,new From: https://www.cnblogs.com/puzi0315/p/17095959.html