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 11111111 255
//就算类型提升前面补的是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();
}
}
/*
11111111111110000000000000000011111111110100101011001
byte类型是一个8位,int是四个8位。
byte:-1 ---->int:-1
1111-1111 ---> byte型的-1
1111-1111 1111-1111 1111-1111 1111-1111 ---> int型的-1
返回值类型是Int类型,类型提升了。
00000000 00000000 00000000 11111111 255
11111111 11111111 11111111 11111111 -1
11111111 --->提升了一个int类型,那不还是-1吗?是-1的原因是因为在8个1前面补的是1导致的。
那么我只要在前面补0,既可以保留原字节数据不变,又可以避免-1的出现。
怎么补0呢?
11111111 11111111 11111111 11111111
&00000000 00000000 00000000 11111111
------------------------------------
00000000 00000000 00000000 11111111
*/
day19/MyBufferedInputStream.java
最新推荐文章于 2022-01-30 10:37:52 发布