JavaIO流(9)

来源:互联网 发布:2016淘宝销售额 编辑:程序博客网 时间:2024/04/30 14:39
/*
演示MP3复制,通过缓冲区
BufferedOutputStream
BufferedInputStream
*/
import java.io.*;
class CopyMp3
{
    public static void copy_1(){
        BufferedOutputStream bos = null;
        BufferedInputStream bis = null;
        try
        {
            bos = new BufferedOutputStream(new FileOutputStream("大海_copy.mp3"));
            bis = new BufferedInputStream(new FileInputStream("F:\\Music\\大海.mp3"));
            int by = 0;
            while((by=bis.read())!=-1){
                bos.write(by);
            }
        }
        catch (IOException e)
        {
            throw new RuntimeException("Mp3文件复制失败");
        }
        finally
        {
            try
            {
                if(bos!=null)
                    bos.close();
            }
            catch (IOException e)
            {
                throw new RuntimeException("缓冲写入流关闭失败");
            }
            try
            {
                if(bis!=null)
                    bis.close();
            }
            catch (IOException e)
            {
                throw new RuntimeException("缓冲读取流关闭失败");
            }
        }
    }
    public static void main(String[] args)
    {
        long start = System.currentTimeMillis();
        copy_1();
        long end = System.currentTimeMillis();
        System.out.println((end-start)+"毫秒");
    }
}
/*自定义BufferedInputStream*/
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{
        //通过in对象读取硬盘上的数据,并存储到buf中。
        if(count==0){
        count = in.read(buf);
        if(count<0)
            return -1;
        pos = 0;
        byte b= buf[pos];
        count--;
        pos++;
        return b&255;
        }
        else if(count>0){
        byte b= buf[pos];
        count--;
        pos++;
        return b&0xff;
        }
        return -1;
    }
    public void myClose() throws IOException{
        in.close();
    }
}
/*
Mp3数据:11111111-11111111-10101010。。。
读一个字节(8位)
连续 11111111即 -1 和判断结束 -1相冲突
返回 整型 int(4个字节32位)
前面补1
 11111111-11111111-11111111-11111111 还是-1
&00000000-00000000-00000000-11111111即255
=00000000-00000000-00000000-11111111 255
read() byte-->int(提升)
write()int-->byte(强转)
*/



原创粉丝点击