java中write(byte[] b)与write(byte[] b,int off,int len)区别


自己说明:

今天在重新学习FileInputSream/FileOutPutSream 读写图片流的时候,发现FileOutPutSream 有两个写的方法。

好像一般人都会用 write(byte[] b,int off,int len)的方法。于是猜,是不是write(byte[] b) 最后一次不满缓冲区长度会有影响。

程序如下:

public class Copic {

    /**
     * @param args
     * @throws IOException
     */
    public static void main(String[] args) throws IOException
    {   
        System.out.println(System.getProperty("user.dir"));
        FileInputStream input = new FileInputStream("src\\com20130725\\resouce\\test.bmp");
        FileOutputStream outPut = new FileOutputStream("src\\com20130725\\resouce\\picCopy.bmp");
        
        int readpicLength=0;
        byte[] bytepic = new byte[1024];
        
        //从输入文件读入 字节流到bytepic input.read(bytepic)
        while(-1 !=(readpicLength= input.read(bytepic)))
        {
            //用这个方法,可能带来一个问题,最后一次可能实际写入会比原来的大(最后一次不满1024个字节的时候)
          //outPut.write(bytepic);
            
            //所以还是带上实际的字节数
          outPut.write(bytepic,0,readpicLength);
            
            
        }
        System.out.println("COPY pic success!");
        outPut.close();
        input.close();
    }

}

经过测试,发现两个方法都可以使用。于是想差别到底在哪里?

网上搜索了下,发现参考了文章:http://liriguang.iteye.com/blog/620610文章。最后一次写入流中的时候,没有按照实际读出的文件写入,而是读入了1024 缓冲区的整数倍。

再仔细查阅了JAVA的源代码,发现如下:

java源代码:

 public void write(byte b[]) throws IOException {
    socketWrite(b, 0, b.length);
    }

 public void write(byte b[], int off, int len) throws IOException {
    socketWrite(b, off, len);
    }

其中,socketWrite是底层的native的方法。

可以看到,write的两个方法,调用的最后一个参数不一样。在逐个读入的时候,write(byte b[])是读入的缓冲区的整数倍,也就是我们上文的1024;

而write(byte b[], int off, int len)读入的是实际读到的大小。

在没有到达最后一次读入的时候,都是一样的。

最后一次不满1024个字节的时候,就有差别了。


做技术还是要仔细啊!

参考了文章:http://liriguang.iteye.com/blog/620610


  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值