import java.io.*;
class BufferedInputStreamDemo
{
public static void main(String[] args) throws IOException
{
MyBufferedInputStream mybis=new MyBufferedInputStream(new FileInputStream("d:\\1.mp3"));
BufferedOutputStream bos=new BufferedOutputStream(new FileOutputStream("d:\\2.mp3"));
int by=0;
while((by=mybis.myRead())!=-1)
{
bos.write(by);
}
mybis.myClose();
bos.close();
}
}
class MyBufferedInputStream
{
private FileInputStream in;
private byte[] buf=new byte[1024*4];//定义缓冲区
private int count=0,pos=0;
MyBufferedInputStream(FileInputStream in)
{
this.in=in;
}
//一个一个读,从缓冲区(字节数组)里读
public int myRead()throws IOException
{
//用count判断缓冲区(字节数组)里的值是否已读完
if(count==0)
{
//从in输入流中将buf.length个字节的数据读入buf数组中。
count=in.read(buf);
if(count<0)//也就是读到是最后,没读到数据
return -1;
//每次往缓冲区写数据时,缓冲区的指针归零
pos=0;
//此myRead方法每次只读一个,所以第一次返回一个buf[0]
byte b=buf[pos];
//buf缓冲区里的字节数-1
count--;
pos++;
/*此处要与上255,因为b是byte型,向上转型为int,为了避免读到的一个字节全是1111-1111
即-1;用255也就是0000-0000 0000-0000 0000-0000 1111-1111与已经向上转型为int的b
1111-1111 1111-1111 1111-1111 1111-1111相与,将0000-0000 0000-0000 0000-0000 1111-1111返回*/
return b&255;
}
else if(count>0)
{
byte b=buf[pos];
count--;
pos++;
return b&255;
}
//此处只是为是让方法有返回
return -1;
}
public void myClose() throws IOException
{
in.close();
}
}
【java编程】IO类之复写BufferedInputStream中read方法
最新推荐文章于 2024-06-11 20:19:37 发布