java-IO小记

说来惭愧,工作一年多了,对io仍然不是很了解。不仅是io,还有网络,还有多线程。shame!!!

接下来的日子里,先搞多线程,再搞io,再搞网络,半年内一定要完成!

好了,今天终于搞懂了outputStream 的三个write的区别,这里小记一下

1.文档里的说明

write(byte[] b) 
          Writes b.length bytes from the specified byte array to this file output stream.

write(byte[] b, int off, int len) 
          Writes len bytes from the specified byte array starting at offset off to this file output stream.

write(int b) 
          Writes the specified byte to this file output stream.

2.理解

① write(byte[] b) 是每次写b.length个字节,即使最后一个byte数组里面没读满,也会写b.lenth个字节

eg:

FileInputStream in = new FileInputStream(new File("C:/Users/admin/Desktop/js/node.txt"));
        byte b[] = new byte[50];
        FileOutputStream out = new FileOutputStream(new File("C:/Users/admin/Desktop/js/node1.txt"));
        int len = 0;
        System.out.println("总长度"+in.available());
        while(( len = in.read(b))!=-1){
            System.out.println(len);
            out.write(b);
        }
        in.close();
        out.flush();
        out.close();

原文件内容

写出的文件

控制台输出

可以看出,由于最后一次读取的字节其实只有4个,但是输出的文件却多了很多(46个字节应该),好像是把上一次读取的内容写入了

所以,即使最后一个byte数组里面没读满,也会写b.lenth个字节

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

off一半是0

len 就是这次该写多少个字节

把上面的代码改为

FileInputStream in = new FileInputStream(new File("C:/Users/admin/Desktop/js/node.txt"));
        byte b[] = new byte[50];
        FileOutputStream out = new FileOutputStream(new File("C:/Users/admin/Desktop/js/node1.txt"));
        int len = 0;
        System.out.println("总长度"+in.available());
        while(( len = in.read(b))!=-1){
            System.out.println(len);
            out.write(b,0,len);
        }
        in.close();
        out.flush();
        out.close();

区别在于out.write 方法

这样的话,写出的文件就没有问题了,最后一次读取4个字节,就写4个字节。

③ write(int b)

Writes the specified byte to this output stream. The general contract for write is that one byte is written to the output stream. The byte to be written is the eight low-order bits of the argument b. The 24 high-order bits of b are ignored.

不懂。。。

原文地址:https://www.cnblogs.com/Iqiaoxun/p/5745690.html