package day06;
import java.io.*;
class MyBufferedInputStream {
private InputStream in;
private byte[] buff=new byte[1024];
private int pos=0,count=0;
MyBufferedInputStream(InputStream in){
this.in=in;
}
//一次读一个字节,从缓冲区(字节数组)获取
public int myRead() throws IOException{
//通过in对象读取硬盘上的数据,并存储到buff中
if(count==0){
count=in.read(buff);
if(count<0){
return -1;
}
pos=0;
byte by=buff[pos];
count--;
}
else if(count>0){
byte by=buff[pos];
count--;
pos++;
return by&255;
}
else{
return -1;
}
}
public void myClose() throws IOException{
in.close();
}
}
import java.io.*;
class MyBufferedInputStream {
private InputStream in;
private byte[] buff=new byte[1024];
private int pos=0,count=0;
MyBufferedInputStream(InputStream in){
this.in=in;
}
//一次读一个字节,从缓冲区(字节数组)获取
public int myRead() throws IOException{
//通过in对象读取硬盘上的数据,并存储到buff中
if(count==0){
count=in.read(buff);
if(count<0){
return -1;
}
pos=0;
byte by=buff[pos];
count--;
pos++;
//由于会出现所读取文件的数据是-1的情况会与返回-1标记相同导致停止,所以将读取的数据与上255转成int类型
return by&255;}
else if(count>0){
byte by=buff[pos];
count--;
pos++;
return by&255;
}
else{
return -1;
}
}
public void myClose() throws IOException{
in.close();
}
}
本文介绍了一个自定义的MyBufferedInputStream类的实现细节,该类模仿了Java标准库中的BufferedInputStream行为,用于提高文件读取效率。文章详细解释了如何从底层输入流读取数据并缓存,以及如何从缓存中逐字节读取。
269

被折叠的 条评论
为什么被折叠?



