NIO:
是一种新的IO流,即new IO,是同步非阻塞IO,其中两个重要组成部分为:channel(通道)和buffer(缓冲区)。
NIO的特性:
1、分散读、聚集写。
分散读是将数据从通道分散读到多个缓冲区里,如图所示:
// 分散读取
public static void main(String[] args) throws FileNotFoundException{
//随机访问
RandomAccessFile random =new RandomAccessFile("text.text","rw");
//访问管道
FileChannel channel =random.getChannel();
//设置缓冲区的大小
ByteBuffer bf1= ByteBuffer.allocate(200);
ByteBuffer bf2= ByteBuffer.allocate(1024);
//分散读
ByteBuffer[] bf={bf1,bf2};
channel.read(bf);
for (ByteBuffer byteBuffer : bf) {
// 切取到读取模式
byteBuffer.flip();
}
System.out.println(new String(bf[0].array(),0,bf[0].limit()));
System.out.println("==============");
System.out.println(new String(bf[1].array(),1,bf[1].limit()));
}
聚集写是将数据从多个缓冲区聚集写进通道里,如下图所示:
NIO与IO的区别
NIO | IO |
---|---|
非阻塞IO | 阻塞IO |
面向缓冲区 | 面向流 |
选择器 | 无 |
IO的形式:通过字节流和字符流对文件进行读写操作。
NIO的形式:通过通道(channel)和缓冲区(buffer)对文件进行读写操作,数据是从通道读入到缓冲区,从缓冲区写入通道中的。