版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Sugar_map/article/details/81320756
本文的核心内容:Java中的I/O模型,Java中的NIO【只涉及chanel和buffer】
Java中的IO模型分类
1. BIO
传统IO 或者 Blocking IO
特点:面向流 Input | Output
2. NIO
New IO 或者 Non Blocking IO
特点:面向缓冲区 Buffer(基于通道)
3. AIO(Async Non Blocking IO)
NIO概述:java.nio全称java non-blocking IO,是指jdk1.4 及以上版本里提供的新api(New IO),为所有的原始类型(boolean类型除外)提供缓存支持的数据容器,使用它可以提供非阻塞式的高伸缩性网络。
NIO的三大组件【Chanel,Buffer,Selector】
Chanel
通道,可读,可写,双向
Channel的主要实现类有:
FileChannel ⽂文件IO
DatagramChannel UDP
SocketChannel TCP Client
ServerSocketChannel TCP Server
Buffer
Buffer的主要实现类有:除boolean外的其余七种基本类型(ByteBuffer、ShortBuffer、IntBuffer等)
一个用于特定基本类型的数据容器,除数据内容外,还包含一下属性:
1. capacity 缓冲区大小- 常量_不可变
2. limit 缓冲区允许读写操作的最大范围
3. position 缓冲区中下一个可读写元素的索引
注:所有可操作的数据在position和limit之间
基于NIO的文件拷贝
public static void main(String[] args) throws Exception {
//创建读通道
FileInputStream fileInputStream = new FileInputStream("D:\\timg.jpg");
FileChannel fileInputStreamChannel = fileInputStream.getChannel();
//创建写通道
FileOutputStream fileOutputStream = new FileOutputStream("D:\\Maps.jpg");
FileChannel fileOutputStreamChannel = fileOutputStream.getChannel();
//创建缓冲区 容量1024byte
ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
//文件拷贝
while (true){
//缓存区设置 回复初始状态
byteBuffer.clear();
//读取内容到缓冲区中 返回读取到的字节长度
int flag = fileInputStreamChannel.read(byteBuffer);
if (flag==-1){
break;
}
//切换读写状态
byteBuffer.flip();
//将缓冲区的内容通过通道写到本地磁盘
fileOutputStreamChannel.write(byteBuffer);
}
System.out.println("文件复制完成!!!");
fileInputStream.close();
fileOutputStream.close();
fileInputStreamChannel.close();
fileOutputStreamChannel.close();
}
Selector【暂不涉及】