ByteBuffer用法

import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.nio.ByteBuffer; public class ByteBufferTest { public static void main(String[] args) {//allocate:分配的意思 ByteBuffer buf = ByteBuffer.allocate(10);//分配10个字节 分配一个新的字节缓冲区。 OutputStream os = new BytebufferBackedOutputStream(buf);//写操作 InputStream is = new ByteBufferBackedInputStream(buf);//读操作 } } class ByteBufferBackedInputStream extends InputStream{ ByteBuffer buf;//字节缓冲区。 ByteBufferBackedInputStream(ByteBuffer buf){//构造方法 this.buf = buf; } @Override//synchronized 同步的 public synchronized int read() throws IOException {//这里实现了InputStream方法 read() // remaining的意思是:剩下的 if(!buf.hasRemaining()){//告知在当前位置和限制之间是否有元素。当且仅当此缓冲区中至少还有一个元素时返回 true return -1; } return buf.get();//返回:缓冲区当前位置的字节 } /** * bytes - 读入数据的缓冲区。 * off - 数组 b 中将写入数据的初始偏移量。 * len - 要读取的最大字节数。 */ public synchronized int read(byte[] bytes,int off,int len) throws IOException{ //将输入流中最多 len 个数据字节读入 byte 数组。remanining()返回:此缓冲区中的剩余元素数 len = Math.min(len,buf.remaining());//返回两个 int 值中较小的一个。 buf.get(bytes,off,len); return len; } } class BytebufferBackedOutputStream extends OutputStream{ ByteBuffer buf; BytebufferBackedOutputStream(ByteBuffer buf){ this.buf = buf; } @Override public synchronized void write(int b) throws IOException {//outputStream的写方法 // TODO Auto-generated method stub buf.put((byte)b); } public synchronized void write(byte[] bytes,int off,int len) throws IOException{ buf.put(bytes,off,len); } }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值