日期:2014-05-20  浏览次数:20753 次

自学java,自定义字节流缓冲区时,小弟有一处代码无法理解,请各位指点迷津
原Code
Java code

/*
需求
自定义字节流缓冲区

*/
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
    {
        //返回为int类型是为了提升返回值的类型
        //通过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
        {
            byte b = buf[pos];

            count--;
            pos++;
            
            return b&0xff;            
        }        
    }
    public void myClose()throws IOException
    {
        in.close();
    }            
}
class MyBufferedInputStreamDemo
{
    public static void main(String[] args)throws IOException
    {
        myCopyMusic();
    }
    public static void myCopyMusic()throws IOException
    {
        MyBufferedInputStream mbis = new MyBufferedInputStream(new FileInputStream("F:\\2.mp3"));
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("F:\\1.mp3"));
        int ch = 0;
        
        while((ch=mbis.myRead())!=-1)
        {
            bos.write(ch);
        }
        bos.close();
        mbis.myClose();
    }
}




注意此处的 if(count<0)
return -1;
按小弟的理解,当文件中数据不满足1024*4个字节,并读到最末位后,会将不满足1024*4个字节的数据存入自己数组buf,并返回-1。
但问题是返回-1后,写入流就会关闭,那么字节数组中剩余的不满1024*4个字节的数据将不会被写入,即复制可能不会成功,字节数组中剩余的数据没被复制。

但经过运行,发现代码是正确的,小弟就有点想不通了,还望各位大哥指点迷津,非常感谢。

------解决方案--------------------
错,实际上这句话:
count = in.read(buf);
的返回值count,代表实际读取的字节数。

也就是最后如果不满4K,假如只读取了 12 个字节,那么count的值就是12。


多看看JDK的API文档吧。
------解决方案--------------------
调用close()是,即使缓存区没有溢满,也会将缓冲区的字节送入目的地
------解决方案--------------------
这是字节流,而且还带有缓冲的! 读完了,最后一次剩多少,它都要往外输出的,不会像LZ想象的那样!!