/*
read()方法返回的是int类型,
是避免 -1 的发生
writer()方法只写最低的字节,保证原数据不变
11111111-11100000
byte: -1 ----> int: -1 ;
11111111
11111111 11111111 11111111 11111111提升为 32位
需要变成
00000000 00000000 00000000 11111111
11111111 --->提升了一个int类型,那不还是-1吗,是-1的原因是在8个1前面补的1导致的
那么只要在前面补0,即可用保留原字节数据不变,又可用避免-1的出现
怎么补0?
11111111 11111111 11111111 11111111
&00000000 00000000 00000000 11111111
------------------------------------
00000000 00000000 00000000 11111111
0000-0001 正数
1111-1110 取反
0000-0001 加一
1111-1111 变 -1
*/
import java.io.*;
class MyBufferedInputStream
{
private InputStream in;
private byte[] buf = new byte[1024*4];
private int pos = 0,count = 0;
MyBufferedInputStream(InputStream in)
{
this.in = in;
}
//一次读一个字节,从缓冲区(字节数组)获取
public int myRead() throws IOException //读一个字节,把它提升为4位,write()有强转动作为1字节
{
//通过in对象读取硬盘上数据,并存储到buf中
if(count==0)
{
count = in.read(buf); //把数据存进buf
if(count<0)
return -1;
pos = 0;//再从0开始读
byte b = buf[pos];//先取0脚标元素
count--;
pos++;
return b&255;
}
else if(count>0)//现为1023了
{
byte b = buf[pos];//现pos为1
count--;
pos++;
return b&0xff;
}
return -1;
}
public void myClose() throws IOException
{
in.close();
}
}
read()方法返回的是int类型,
是避免 -1 的发生
writer()方法只写最低的字节,保证原数据不变
11111111-11100000
byte: -1 ----> int: -1 ;
11111111
11111111 11111111 11111111 11111111提升为 32位
需要变成
00000000 00000000 00000000 11111111
11111111 --->提升了一个int类型,那不还是-1吗,是-1的原因是在8个1前面补的1导致的
那么只要在前面补0,即可用保留原字节数据不变,又可用避免-1的出现
怎么补0?
11111111 11111111 11111111 11111111
&00000000 00000000 00000000 11111111
------------------------------------
00000000 00000000 00000000 11111111
0000-0001 正数
1111-1110 取反
0000-0001 加一
1111-1111 变 -1
*/
import java.io.*;
class MyBufferedInputStream
{
private InputStream in;
private byte[] buf = new byte[1024*4];
private int pos = 0,count = 0;
MyBufferedInputStream(InputStream in)
{
this.in = in;
}
//一次读一个字节,从缓冲区(字节数组)获取
public int myRead() throws IOException //读一个字节,把它提升为4位,write()有强转动作为1字节
{
//通过in对象读取硬盘上数据,并存储到buf中
if(count==0)
{
count = in.read(buf); //把数据存进buf
if(count<0)
return -1;
pos = 0;//再从0开始读
byte b = buf[pos];//先取0脚标元素
count--;
pos++;
return b&255;
}
else if(count>0)//现为1023了
{
byte b = buf[pos];//现pos为1
count--;
pos++;
return b&0xff;
}
return -1;
}
public void myClose() throws IOException
{
in.close();
}
}