首页 > 代码库 > 字节流复制mp3文件(带缓冲区)

字节流复制mp3文件(带缓冲区)

//自定义的缓冲区

import java.io.*;


class  MyBufferedInputStream
{
    private byte[] buf = new byte[1024];

    private InputStream in;
   
    private int pos = 0, count = 0;

    MyBufferedInputStream(InputStream in){
        this.in = in;
    }
   
    /*
        一次读一个字节,从缓冲区字节数组中读。
    */
    public int myRead(){
        //通过in对象读取硬盘数据,并存储buf中
        if(count == 0){
            count = in.read(buf);
            if(count < 0)
                return -1;
            pos = 0;
            byte b = buf[pos];
            count--;
            pos++;
            return b;
        }else if(count > 0){
            byte b = buf[pos];
            count--;
            pos++;
            return b;
        }
        return -1;
    }

    public void myClose(){
        in.close();
    }
   
}

 

调用缓冲区:

import java.io.*;class CopyMp3 {    public static void main(String[] args) throws Exception     {        long start = System.currentTimeMillis();        copy_1();        long end = System.currentTimeMillis();        System.out.println(end- start);    }    //通过字节流的缓冲区完成复制    public static void copy_2() throws Exception{        BufferedInputStream bufis = new BufferedInputStream(new FileInputStream("c:\\1.mp3"));        BufferedOutputStream bufos = new BufferedOutputStream(new FileOutputStream("c:\\2.mp3"));        int by = 0;        while((by = bufis.myRead()) != -1){            bufos.write(by);        }        bufos.close();        bufis.myClose();    }}

 

-----------------------

问题:

被复制的文件出现0字节

0000-0001

1111-1110

1111-1111

 

byte:-1 ---> int:-1

他会让前面加1,为了让前面补0,需要&255

 

最低四位&15 

1 1 1 1

最低八位&255

1111   1111