- import java.io.*;
- class MyBufferedInputStream {
- //定义一个要被修饰的类
- private InputStream in;
- //定义一个字节型的数组
- private byte[] buf=new byte[1024];
- //定义两个变量,一个做指针,一个做计数器
- private int pos=0,count=0;
- //构造函数,向构造函数里面添加被修饰的类
- public MyBufferedInputStream(InputStream in){
- this.in=in;
- }
- //自定义一个read方法
- public int myRead()throws IOException{
- //计数器大于0时,
- if (count>0) {
- byte b=buf[pos];
- count--;
- pos++;
- return b&15;
- }else if (count==0) {//计数器为零时,说明数组中的元素被取完了,需要重新获取
- count=in.read(buf);
- //数组获取不到元素,说明已经读取完毕
- if (count<0) {
- return -1;
- }
- //将指针置为数组的0角标
- pos=0;
- byte b=buf[pos];
- count--;
- pos++;
- return b&15;
- }
- return -1;
- }
- public void myClose()throws IOException{
- in.close();
- }
-
- }
复制代码
read方法都到最后为了防止第一次读到的就是-1,会把读到的字节&15提升到int类型,所以返回来的是int型数据 |