Netty源码分析 -----HeapByteBuffer与HeapByteBufferR

public static void main(String[] args) {
        ByteBuffer buffer = java.nio.ByteBuffer.allocate(10);
        System.out.println("buffer type class: "+ buffer.getClass());//java.nio.HeapByteBuffer
        ByteBuffer readOnlyBuffer = buffer.asReadOnlyBuffer();
        System.out.println("readOnlyBuffer type class: "+ readOnlyBuffer.getClass());//java.nio.HeapByteBufferR
    }
   protected HeapByteBufferR(byte[] buf, int mark, int pos, int lim, int cap, int off)
   {   
super(buf, mark, pos, lim, cap, off);      
this.isReadOnly = true; 
}

一、入门demo

从上面的代码我们可以看出默认的申请一个10byte长度的数组默认是HeapByteBuffer。

当我们把buffer转化为readonly模式的时候它其实内部又new了一个HeapByteBufferR。设置成员变量isReadOnly为true

public abstract class ByteBuffer   extends Buffer   implements Comparable<ByteBuffer>
{
    final byte[] hb;     //元素数组  
    final int offset;    //下标偏移量,从offset+index确定数组中的位置
    boolean isReadOnly;  //是否只读
}

二、API操作

package demo1;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import io.netty.buffer.ByteBuf;
public class demo2 {	
	public static void main(String[] args) throws Exception {
		FileInputStream inputStream = new FileInputStream("input.txt");
		FileOutputStream outputStream = new FileOutputStream("output.txt");
		
		FileChannel inputChannel =inputStream.getChannel();
		FileChannel outputChannel = outputStream.getChannel();
		
		ByteBuffer buffer = ByteBuffer.allocate(512);
		
		while(true) {
            //clear 后position=0 limit=capacity mark=-1
			buffer.clear();
            //底层调用了IOUtil类write()调用了buffer.put()方法
			int read = inputChannel.read(buffer);//position++,这里注意若数据没有读完但是buffer满了,那么返回0.如数据已经读完返回-1
			System.out.println("read:"+read);
			if(-1 == read) {
				break;
			}
			buffer.flip();//limit= position;position=0; 
             //底层调用了buffer.get()方法
			outputChannel.write(buffer);//position++
		}
		inputChannel.close();
		outputChannel.close();
	}
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值