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);
}
}
ByteBuffer用法
最新推荐文章于 2022-04-09 18:34:53 发布