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

来源:互联网 发布:mac pro 需要的配件 编辑:程序博客网 时间:2024/06/05 08:23

    在进行写文件的时候有时候返现,通过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。


阅读全文
0 0
原创粉丝点击