Java NIO使用(上)
创始人
2025-05-29 10:23:14
0

1. NIO使用

1.1 Buffer

以IntBuffer为例,初始化一个Buffer,InputBuffer是一个抽象类,是Buffer的子类:

//初始化buffer,allocate方法用于初始化,参数是缓冲区容量
IntBuffer buffer = IntBuffer.allocate(10);

查看InputBuffer源码:

public static IntBuffer allocate(int capacity) {if (capacity < 0)throw new IllegalArgumentException();return new HeapIntBuffer(capacity, capacity);
}

可以看到实际返回的是HeapIntBuffer的对象,继续查看HeapIntBuffer源码:

HeapIntBuffer(int cap, int lim) {            // package-privatesuper(-1, 0, lim, cap, new int[cap], 0);/*hb = new int[cap];offset = 0;*/
}

区中的super调用的是IntBuffer中的构造方法:

IntBuffer(int mark, int pos, int lim, int cap,   // package-privateint[] hb, int offset)
{super(mark, pos, lim, cap);this.hb = hb;this.offset = offset;
}

其中几个参数说明如下: cap是capacity,即容量,就是缓冲区的大小
hb是一个数组,是缓冲区实际存储数据的地方,数组大小根据capacity值设定
pos是position,表示位置,是一个标记。表示缓冲区(hb)中当前要读取或写入的数据位置
lim是limit,在写入的时候,它的值和capacity一致,读取的时候,它是缓冲区中数据的实际长度 offset是偏移量 mark是标记
这些参数的作用,具体要看写入和读取的代码 写入数据使用put方法:

//初始化buffer,allocate方法用于初始化,参数是缓冲区容量
IntBuffer buffer = IntBuffer.allocate(10);
buffer.put(1);//写入数字1
buffer.put(2);//写入数字2

查看HeapIntBuffer中的源码:

public IntBuffer put(int x) {hb[ix(nextPutIndex())] = x;return this;
}

可以看到是在hb数组中放入要写入的数字,放入的位置通过nextPutIndex()和ix()两个方法获得:

final int nextPutIndex() {                          // package-privateif (position >= limit)throw new BufferOverflowException();return position++;
}

可以看到,在方法中判断了position和limit的大小,在缓冲区初始化的时候,position是0,limit是缓冲区的大小,如果要放入的索引位置超出了缓冲区大小,就抛出异常。第一个写入的位置position是0,之后position++,即下一次从索引1开始写入。

protected int ix(int i) {return i + offset;
}

ix()方法用于计算偏移后的位置。因为开始的时候offset=0,所以默认是不偏移的。 对于已经写入得效果,我们可以输出缓冲区中的数组:

System.out.println(Arrays.toString(buffer.array()));

其中array()返回的就是前面说到的数组hb,即缓冲区实际存放数据的地方,源码如下:

public final int[] array() {if (hb == null)throw new UnsupportedOperationException();if (isReadOnly)throw new ReadOnlyBufferException();return hb;
}

运行效果如下图: 在array()方法中看到了一个isReadOnly属性,顾名思义,它是设置只读的
查看源码:

public IntBuffer asReadOnlyBuffer() {return new HeapIntBufferR(hb,this.markValue(),this.position(),this.limit(),this.capacity(),offset);
}

asReadOnlyBuffer()方法创建了一个新的HeapIntBufferR(注意后面多了个R,不是原来的HeapIntBuffer了),新缓冲区的属性和当前的对象一致,并且新缓冲区把isReadOnly属性设置成了true

protected HeapIntBufferR(int[] buf,int mark, int pos, int lim, int cap,int off)
{super(buf, mark, pos, lim, cap, off);this.isReadOnly = true;
}

HeapIntBufferR的put()方法是不能写入的:

public IntBuffer put(int x) {throw new ReadOnlyBufferException();
}

Buffer是既可以写入,又可以读取的。默认是写入模式。如果想读取已经写入的内容,需要切换读写模式:

IntBuffer buffer = IntBuffer.allocate(10);
buffer.put(1);//写入数字1,写完之后position是1
buffer.put(2);//写入数字2,写完之后position是2
buffer.flip();//切换到读
while (buffer.hasRemaining()) {System.out.println(buffer.get());
}

首先看get()方法,get()用于读取缓冲区数组中的元素,每次返回一个元素,查看源码:

public int get() {return hb[ix(nextGetIndex())];
}
final int nextGetIndex() {                          // package-privateif (position >= limit)throw new BufferUnderflowException();return position++;
}

可以看到返回的是第position个位置的元素。但是position在put()写入的时候记录的是下一次该写入的位置,如果直接从position开始读,是读不到数据的。所以需要flip()方法:

public final Buffer flip() {limit = position;position = 0;mark = -1;return this;
}

flip()方法中,limit=position,即已经写入的数据长度,设置position=0,之后再读取的时候,就是从索引0开始读的了。每次读取一个元素,position自增1。

public final boolean hasRemaining() {return position < limit;
}

hasRemainig()中对position和limit进行判断,保证不会读取的数据不会超出写入的部分。
所以capacity>limit>position
因为读取之后,重置了position和limit,所以不能再继续写入了。需要从读模式再切换回写模式:
从写切换到读有两个方法,clear()和compact()

//初始化buffer
IntBuffer buffer = IntBuffer.allocate(10);
buffer.put(1);//写入数字1
buffer.put(2);//写入数字2
buffer.flip();//切换到读
System.out.println(buffer.get());//读取的是数字1,数字2未读取
System.out.println("===================");
//buffer.clear();//切换到写模式,后写入的数据覆盖原来的内容
buffer.compact();//切换到写模式,不清除未读取的数据
buffer.put(3);
buffer.put(4);
buffer.flip();//切换到读
while (buffer.hasRemaining()) {System.out.println(buffer.get());
}

上面的代码,用clear()之后,输出第二次读取输出的是34,2被后写入的3覆盖了;用compact(),第二次输出的是234,因为2没有被读取,被保留,3和4会在它之后写入。
clear()方法之后,position=0,写入的数据会覆盖以前的数据;而compact()方法会保留未读的数据(注意只是未读的,已经写入的数据如果读取过了就不会保留)。

public final Buffer clear() {position = 0;limit = capacity;mark = -1;return this;
}
public IntBuffer compact() {System.arraycopy(hb, ix(position()), hb, ix(0), remaining());position(remaining());limit(capacity());discardMark();return this;
}
public final int remaining() {return limit - position;
}

clear()方法比较直观,把position重置为0,下次就从索引0开始写入,所以后写入的数据会覆盖原来位置的数据。
compact()方法里,可以看到这里调用了一个数组复制的方法,查看几个参数的意义:

public static native void arraycopy(Object src,  int  srcPos,Object dest, int destPos,int length);

src是原始数组,srcPos是从原始数组的第几个位置开始复制,desc是目标数组,destPos是目标数组开始写入的位置,length是从原始数组中复制几个元素到目标数组中。
在读取模式的时候,position是读取的位置,limit是一共有多少数据,remaining()中limit-position就是还有几个是没有读取的。
复制数组的之后,从position开始复制,到新数组,一共复制remaining个,就是把没有读取的数据都复制到新数组去,destPos=0,就是从新数组的索引0开始插入。所以compact()方法是把原来缓冲区中没有读取的数据全部放放到新缓冲区的头部,新插入的数据在头部之后。
通过上面的案例可以看出,所谓的读模式和写模式,就通过改变position和limit的值,对数组中指定位置的元素进行操作。
另外两个和position方法,mark()和reset(),mark()用于记录当前position,reset()可以将position恢复到mark()记录的值。

IntBuffer buffer = IntBuffer.allocate(10);
buffer.put(1);//写入数字1
buffer.put(2);//写入数字2
buffer.mark();//对position进行标记,当前mark=2
System.out.println("get之前:"+buffer.position());//2
System.out.println(buffer.get());//输出0,position++,position=3
System.out.println("get之后:"+buffer.position());//3
buffer.reset();//重置position,position等于mark标记值2
System.out.println("reset之后:"+buffer.position());//2

1.2 FileChannel

FileChannel写文件:

FileOutputStream outputStream = new FileOutputStream("G:/file_channel.txt");
FileChannel channelOut = outputStream.getChannel();
ByteBuffer buffer = ByteBuffer.allocate(1024);
String string = "你好";
buffer.put(string.getBytes());
buffer.flip(); // 切换到读模式
channelOut.write(buffer); //把buffer中的数据写入channel
channelOut.close();
outputStream.close();

java1.7之后提供的新的打开FileChannel的方式:

FileChannel channel = FileChannel.open(Paths.get("D://test.txt"), StandardOpenOption.CREATE,StandardOpenOption.WRITE);

注意在调用channel的write方法之前必须调用buffer的flip方法,否则无法正确写入内容 FileChannel读文件:

FileInputStream inputStream = new FileInputStream("G:/ip.txt");
FileChannel channelIn=inputStream.getChannel();
ByteBuffer buf = ByteBuffer.allocate(128);
int len=-1;
while((len=channelIn.read(buf))!=-1){buf.flip();//从写模式切换到读模式
byte[] arr = new byte[len];buf.get(arr, 0, len); //讲buffer中的数据写入arrSystem.out.println(new String(arr,"GBK"));buf.compact();//让Buffer准备再次写入
}
channelIn.close();
inputStream.close();

java1.7之后提供的新的打开FileChannel的方式:

FileChannel channel = FileChannel.open(Paths.get("D://test.log"), StandardOpenOption.READ);

使用FileChannel复制文件:

FileInputStream fileInputStream = new FileInputStream("G:/java.zip");
FileOutputStream fileOutputStream = new FileOutputStream("G:/java2.zip");
// 得到fileInputStream的文件通道
FileChannel fileChannelInput = fileInputStream.getChannel();
// 得到fileOutputStream的文件通道
FileChannel fileChannelOutput = fileOutputStream.getChannel();
// 将fileChannelInput通道的数据,写入到fileChannelOutput通道
fileChannelInput.transferTo(0, fileChannelInput.size(), fileChannelOutput);
fileInputStream.close();
fileChannelInput.close();
fileOutputStream.close();
fileChannelOutput.close();

transferTo方法文件大小限制在2G以内,可以直接使用缓冲区,不受限制。

FileChannel in = FileChannel.open(Paths.get("D://test.log"), StandardOpenOption.READ);
FileChannel out = FileChannel.open(Paths.get("D://test.txt"), StandardOpenOption.CREATE, StandardOpenOption.WRITE);
ByteBuffer buffer = ByteBuffer.allocate(1024);
while (in.read(buffer) != -1) {buffer.flip();//从写模式切换到读模式out.write(buffer);buffer.clear();//让Buffer准备再次写入
}
out.close();
in.close();

相关内容

热门资讯

【MySQL】锁 锁 文章目录锁全局锁表级锁表锁元数据锁(MDL)意向锁AUTO-INC锁...
【内网安全】 隧道搭建穿透上线... 文章目录内网穿透-Ngrok-入门-上线1、服务端配置:2、客户端连接服务端ÿ...
GCN的几种模型复现笔记 引言 本篇笔记紧接上文,主要是上一篇看写了快2w字,再去接入代码感觉有点...
数据分页展示逻辑 import java.util.Arrays;import java.util.List;impo...
Redis为什么选择单线程?R... 目录专栏导读一、Redis版本迭代二、Redis4.0之前为什么一直采用单线程?三、R...
【已解决】ERROR: Cou... 正确指令: pip install pyyaml
关于测试,我发现了哪些新大陆 关于测试 平常也只是听说过一些关于测试的术语,但并没有使用过测试工具。偶然看到编程老师...
Lock 接口解读 前置知识点Synchronized synchronized 是 Java 中的关键字,...
Win7 专业版安装中文包、汉... 参考资料:http://www.metsky.com/archives/350.htm...
3 ROS1通讯编程提高(1) 3 ROS1通讯编程提高3.1 使用VS Code编译ROS13.1.1 VS Code的安装和配置...
大模型未来趋势 大模型是人工智能领域的重要发展趋势之一,未来有着广阔的应用前景和发展空间。以下是大模型未来的趋势和展...
python实战应用讲解-【n... 目录 如何在Python中计算残余的平方和 方法1:使用其Base公式 方法2:使用statsmod...
学习u-boot 需要了解的m... 一、常用函数 1. origin 函数 origin 函数的返回值就是变量来源。使用格式如下...
常用python爬虫库介绍与简... 通用 urllib -网络库(stdlib)。 requests -网络库。 grab – 网络库&...
药品批准文号查询|药融云-中国... 药品批文是国家食品药品监督管理局(NMPA)对药品的审评和批准的证明文件...
【2023-03-22】SRS... 【2023-03-22】SRS推流搭配FFmpeg实现目标检测 说明: 外侧测试使用SRS播放器测...
有限元三角形单元的等效节点力 文章目录前言一、重新复习一下有限元三角形单元的理论1、三角形单元的形函数(Nÿ...
初级算法-哈希表 主要记录算法和数据结构学习笔记,新的一年更上一层楼! 初级算法-哈希表...
进程间通信【Linux】 1. 进程间通信 1.1 什么是进程间通信 在 Linux 系统中,进程间通信...
【Docker】P3 Dock... Docker数据卷、宿主机与挂载数据卷的概念及作用挂载宿主机配置数据卷挂载操作示例一个容器挂载多个目...