【java编程】IO类之复写BufferedInputStream中read方法

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();
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值