一、什么是NIO
1.概念
NIO是java1.4中引入的,被称为new I/O,也有说是non-blocking I/O,NIO被成为同步非阻塞的IO。
2.跟BIO流的区别
-
BIO是面向流的,NIO是面向块(缓冲区)的。
-
BIO的流都是同步阻塞的,而NIO是同步非阻塞的。
-
NIO会等待数据全部传输过来再让线程处理,BIO是直接让线程等待。
-
NIO有选择器,而BIO没有。
-
NIO是采用管道和缓存区的形式来处理数据的,而BIO是采用输入输出流来处理的。
-
NIO是可以双向的,BIO只能够单向。
二、NIO常用组件Channel和Buffer的使用
1.代码
这里以文件复制为例
public class test {
public static void main(String[] args){
try{
//存在的照片
File inFile=new File("C:\\Users\\Administrator\\Desktop\\study.PNG");
//复制后要存放照片的地址
File outFile=new File("C:\\Users\\Administrator\\Desktop\\study1.PNG");
//打开流
FileInputStream fileInputStream=new FileInputStream(inFile);
FileOutputStream fileOutputStream=new FileOutputStream(outFile);
/**
* RandomAccessFile accessFile=new RandomAccessFile(inFile,"wr");
* FileChannel inFileChannel=accessFile.getChannel();
* 和下面两行代码是一样的,都是可以拿到FileChannel
*/
//获取Channel
FileChannel inFileChannel=fileInputStream.getChannel();
FileChannel outFileChannel=fileOutputStream.getChannel();
//创建buffer
ByteBuffer buffer=ByteBuffer.allocate(1024*1024);
//读取到buffer中
while (inFileChannel.read(buffer)!=-1){
//翻转一下,就可以读取到全部数据了
buffer.flip();
outFileChannel.write(buffer);
//读取完后要clear
buffer.clear();
}
//关闭
inFileChannel.close();
outFileChannel.close();
fileInputStream.close();
fileOutputStream.close();
}catch (Exception e){}
}
}
我的桌面上的确多了一张一模一样的图片
2.解释
使用NIO的话,需要注意几个步骤:
-
打开流
-
获取通道
-
创建Buffer
-
切换到读模式 buffer.flip()
-
切换到写模式 buffer.clear(); 其实这里也看不出来它是怎么使用缓冲区的,上面这段代码中的while循环的作用和下面的代码是一样的
while ((i=fileInputStream.read())!=-1){
fileOutputStream.write(i);
}