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();

相关内容

热门资讯

安卓系统换成苹果键盘,键盘切换... 你知道吗?最近我在想,要是把安卓系统的手机换成苹果的键盘,那会是怎样的体验呢?想象那是不是就像是在安...
小米操作系统跟安卓系统,深度解... 亲爱的读者们,你是否曾在手机上看到过“小米操作系统”和“安卓系统”这两个词,然后好奇它们之间有什么区...
miui算是安卓系统吗,深度定... 亲爱的读者,你是否曾在手机上看到过“MIUI”这个词,然后好奇地问自己:“这玩意儿是安卓系统吗?”今...
安卓系统开机启动应用,打造个性... 你有没有发现,每次打开安卓手机,那些应用就像小精灵一样,迫不及待地跳出来和你打招呼?没错,这就是安卓...
小米搭载安卓11系统,畅享智能... 你知道吗?最近小米的新机子可是火得一塌糊涂,而且听说它搭载了安卓11系统,这可真是让人眼前一亮呢!想...
安卓2.35系统软件,功能升级... 你知道吗?最近在安卓系统界,有个小家伙引起了不小的关注,它就是安卓2.35系统软件。这可不是什么新玩...
安卓系统设置来电拦截,轻松实现... 手机里总是突然响起那些不期而至的来电,有时候真是让人头疼不已。是不是你也想摆脱这种烦恼,让自己的手机...
专刷安卓手机系统,安卓手机系统... 你有没有想过,你的安卓手机系统是不是已经有点儿“老态龙钟”了呢?别急,别急,今天就来给你揭秘如何让你...
安卓系统照片储存位置,照片存储... 手机里的照片可是我们珍贵的回忆啊!但是,你知道吗?这些照片在安卓系统里藏得可深了呢!今天,就让我带你...
华为鸿蒙系统不如安卓,挑战安卓... 你有没有发现,最近手机圈里又掀起了一股热议?没错,就是华为鸿蒙系统和安卓系统的较量。很多人都在问,华...
安卓系统陌生电话群发,揭秘安卓... 你有没有遇到过这种情况?手机里突然冒出好多陌生的电话号码,而且还是一个接一个地打过来,简直让人摸不着...
ios 系统 安卓系统对比度,... 你有没有发现,手机的世界里,iOS系统和安卓系统就像是一对双胞胎,长得差不多,但细节上却各有各的特色...
安卓只恢复系统应用,重拾系统流... 你有没有遇到过这种情况?手机突然卡顿,或者某个应用突然罢工,你一气之下,直接开启了“恢复出厂设置”大...
安卓系统出现支付漏洞,揭秘潜在... 你知道吗?最近安卓系统可是闹出了不小的风波呢!没错,就是那个我们每天离不开的安卓系统,竟然出现了支付...
苹果换了安卓系统恢复,体验变革... 你有没有遇到过这种情况?手机里的苹果突然变成了安卓系统,而且还是那种让你摸不着头脑的恢复模式。别急,...
安卓怎么卸载系统app,轻松告... 手机里的系统应用越来越多,有时候真的让人眼花缭乱。有些应用虽然看起来很实用,但用起来却发现并不适合自...
安卓系统查看步数,揭秘日常运动... 你有没有发现,每天手机里的小秘密越来越多?今天,咱们就来聊聊安卓系统里那个悄悄记录你每一步的小家伙—...
安卓系统未来会不会,未知。 你有没有想过,那个陪伴我们手机生活的安卓系统,它的未来会怎样呢?想象每天早上醒来,手机屏幕上跳出的信...
安卓系统怎么设置截图,轻松捕捉... 亲爱的手机控们,你是不是也和我一样,有时候想记录下手机屏幕上的精彩瞬间呢?别急,今天就来手把手教你如...
安卓系统下载软件安装,安卓系统... 你有没有发现,手机里的安卓系统就像一个巨大的宝藏库,里面藏着各种各样的软件,让人眼花缭乱。今天,就让...