package com.laien.io;
import java.io.IOException;
import java.io.InputStream;
/**
* 自定义InputStream,节点流
*
* @author Administrator
*
*/
public class MyByteArrayInputStream extends InputStream {
protected byte[] arr; // 数据源
protected int ptr = 0; // 当前指针
protected int mark=0;//标记
/**
* 构造函数,接收输入的字节数组
* @param arr
*/
public MyByteArrayInputStream(byte[] arr) {
this.arr = arr;
}
/**
* 抽象方法,必须实现
*/
@Override
public int read() throws IOException {
//当读到没有数据后,会返回-1
return (ptr < arr.length) ? arr[ptr++] : -1;
}
/**
* 可读数据长度
*/
@Override
public int available() throws IOException {
return arr.length - ptr;
}
@Override
public void close() throws IOException {
ptr = arr.length;
}
/**
* 标记,与reset相应
*/
@Override
public synchronized void mark(int readlimit) {
this.mark = readlimit;
}
@Override
public synchronized void reset() throws IOException {
if (this.mark<0 || this.mark >= arr.length) {
throw new IOException("标识不对");
}
ptr = mark;//指针重新指到mark位置,让流可以重新读取
}
/**
* 重写方法
*/
@Override
public int read(byte[] b, int off, int len) throws IOException {
if (ptr >= arr.length || len <0) {
//流已读完
return -1;
}
if (len == 0) {
return 0;
}
//处理最后一次读取的时候可能不没有len的长度,取实际长度
len = available() < len ? available() : len;
System.arraycopy(arr, ptr, b, off, len);
ptr += len;
//返回读取的长度
return len;
}
public static void main(String[] args) throws IOException {
//测试
byte[] source = new byte[10];
for (int i=0; i<source.length; i++) {
source[i] = (byte)i;
}
MyByteArrayInputStream mis = new MyByteArrayInputStream(source);
byte[] buff = new byte[4]; //
int len =0;
while(-1 != (len = mis.read(buff, 0, buff.length))) {
for (int i=0; i<len; i++) {
System.out.print(buff[i]);
}
System.out.println();
}
}
}