如何实现自己的输入流

时间:2021-01-22 00:10:54


1、 首先必须继承InputStream

2、实现read方法

3、由于ptr位置的使用,使得流的访问,一次必须读完。


public class MyownStream extends InputStream

{
    protected byte[] data;
    protected int ptr;
    protected int mark = 0;
    public MyownStream(byte[] b)
    {
    data = b;
    }
@Override
public int read() throws IOException {

return ptr>data.length ? (data[ptr++]):-1;
}
@Override
public int available() throws IOException {

return data.length - ptr;
}
@Override
public void close() throws IOException {
ptr = data.length;
}
@Override
public synchronized void reset() throws IOException {
if(mark == 0 || mark > data.length)
{
throw new IOException("the position is available");
}
else 
{
  ptr = mark;
}
}
@Override
public boolean markSupported() {
return true;
}
@Override
public int read(byte[] b, int off, int len) throws IOException {
   int length = -1;
if(ptr >= data.length || len < 0)
   {
length = -1;
   }
   if(ptr +data.length > data.length )
   {
    length =  data.length - ptr;
   }
   if(len == 0)
   {
    length = 0;
   }
   return length;
}

}