write(byte b[], int off, int len)与write(byte b[])

    在进行写文件的时候有时候返现,通过write(byte b[])方式写文件比原来的文件大一些。流程代码:

   public static void main(String[] args) throws Exception {
        long t1 = System.currentTimeMillis();
        File file = new File("d:/11.jpg");
        FileInputStream in = new FileInputStream(file);
        BufferedInputStream brin = new BufferedInputStream(in, 1024);

        File outFile = new File("d:/112.jpg");
        FileOutputStream out = new FileOutputStream(outFile);
        BufferedOutputStream bout = new BufferedOutputStream(out);
        byte input[] = new byte[1024];
        while ((brin.read(input))!= -1) {
            bout.write(input);
        }
        bout.close();
        out.flush();
        out.close();
        System.out.println((System.currentTimeMillis() - t1));
    }
看了下write(byte b[])的实现是

 public void write(byte b[]) throws IOException {
        write(b, 0, b.length);
    }
当在while循环里面写文件时,在最后一次如果剩余是562个byte;由于读取暂存到的byte是1024大小,write(byte b[])底层实现是偏移量是0,大小是byte的长度,所以最后一次写及时562任然写入1024。所以在最终写入的结果里面是比原始图片要大一些。那么需要改为,读到多少写多少。

public static void main(String[] args) throws Exception {
        long t1 = System.currentTimeMillis();
        File file = new File("d:/餐巾纸.jpg");
        FileInputStream in = new FileInputStream(file);
        BufferedInputStream brin = new BufferedInputStream(in, 1024*5);

        File outFile = new File("d:/餐巾纸2.jpg");
        FileOutputStream out = new FileOutputStream(outFile);
        BufferedOutputStream bout = new BufferedOutputStream(out);
        byte input[] = new byte[1024*5];
        int count;
        while ((count=brin.read(input))!= -1) {
            bout.write(input,0,count);
        }
        bout.close();
        out.flush();
        out.close();
        System.out.println((System.currentTimeMillis() - t1));
    }
总结:

write(byte b[], int off, int len)表示:

b 这一次写的数据

off 这次从b的第off开始写

len 这次写的长度。

public int read(byte[] b, int off, int len)
  • b -- 目标字节数组。

  • off -- 将读取的数据写入到数组b中,off表示从数据b的哪个位置开始写。

  • len -- 要读取的字节数。

  • IOException -- 如果发生I/ O错误。

  • NullPointerException -- 如果b为 null.

  • IndexOutOfBoundsException -- 如果off为负,len为负,或len大于b.length - off。

该方法返回读入缓冲区的总字节数,或如果没有更多的数据,因为数据流的末尾已到达返回-1。


  • 4
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值