Java NIO使用(上)

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-private
    super(-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-private
             int[] 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-private
    if (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-private
    if (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中的数据写入arr
	System.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();
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

专治八阿哥的孟老师

您的鼓励是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值