自定义字节流缓冲区read(),write()的特点

来源:互联网 发布:怎么买淘宝小号 编辑:程序博客网 时间:2024/06/08 13:45
/*自定义字节流缓冲区read(),write()的特点read()和write()的返回值int是4个字节,32个byteread()的特点,因为read()方法byte转int,8位转32位,所以为了防止第一个字节(8个byte)变32个1(即为-1),与上8个1(即为255)write()的特点,int强转byte,去除前3个字节,只保留最后1个字节。*/import java.io.*;class  MyBufferdInputStream{    private InputStream in;//抽象的超类    private byte buf = new byte[1024];    private int pos = 0,count=0;//下标,计数器    MyBufferdInputStream(InputStream in)//构造器,多态参数    {        this.in = in;    }    public int myRead() throws IOException//一次读一个字节,从缓冲区(字节数组)    {        //通过in对象读取硬盘上数据,并存储buf中        if(count ==0)        {            count = in.read(buf);//计数器,read(char []) 返回总字符数                if (count<0)                                return -1;                      pos = 0;//下标清零            byte b = buf[pos];            count --;            pos++;            return b&0xff;//因为read()方法byte转int,8位转32位,所以为了防止第一个字节(8个byte)变32个1(即为-1),与上8个1(即为255)        }        else if (count>0)        {            byte b = buf[pos];//写入数组            count --;            pos++;            return b&0xff;        }        return -1;    }    public void myClose() throws IOException//自定义关闭方法    {        in.close();    }}
0 0