day19/MyBufferedInputStream.java

来源:互联网 发布:中银淘宝卡办理 编辑:程序博客网 时间:2024/05/19 17:07
import java.io.*;class MyBufferedInputStream {private InputStream in;private int pos=0,count=0;private byte[] buf = new byte[1024];//一次读一个字节,从缓冲区(字节数组)获取。MyBufferedInputStream(InputStream in){this.in = in;}public int myRead() throws IOException{//通过in对象读取硬盘上的数据,并存储buf中。if(count==0){count = in.read(buf);if(count<0)return -1;pos=0;byte b = buf[pos];pos++;count--;return b&255;//不和255作与运算,就会出现拷贝的文件是0字节。 //因为要取四个8位中的有效位:低8位 00000000 00000000 00000000 11111111255 //就算类型提升前面补的是1,也可以保证有效位低8位是255.}else if(count>0){byte b = buf[pos];pos++;count--;return b&0xff;}return -1;}public void myClose()throws IOException{in.close();}}/*11111111111110000000000000000011111111110100101011001byte类型是一个8位,int是四个8位。byte:-1 ---->int:-11111-1111---> byte型的-11111-1111 1111-1111 1111-1111 1111-1111  ---> int型的-1返回值类型是Int类型,类型提升了。00000000 00000000 00000000 1111111125511111111 11111111 11111111 11111111-111111111 --->提升了一个int类型,那不还是-1吗?是-1的原因是因为在8个1前面补的是1导致的。那么我只要在前面补0,既可以保留原字节数据不变,又可以避免-1的出现。怎么补0呢? 11111111 11111111 11111111 11111111&00000000 00000000 00000000 11111111------------------------------------ 00000000 00000000 00000000 11111111*/

0 0