IO流系列一:输入输出流的转换

输入流转字节数组的原理
1、读取输入流,每一小段 读一次,取出 byteArray 。
2、将该一小段byteArray写入到字节输出流ByteOutStream。直到不能从输入流再读出字节为止。
3、将字节输出流转成字节数组。

源码:

public class ByteToInputStream {  
  
    public static final InputStream byte2Input(byte[] buf) {  
        return new ByteArrayInputStream(buf);  
    }  
  
    public static final byte[] input2byte(InputStream inStream)  
            throws IOException {  
        ByteArrayOutputStream swapStream = new ByteArrayOutputStream();  
        byte[] buff = new byte[100];  
        int rc = 0;  
        while ((rc = inStream.read(buff, 0, 100)) > 0) {  
            swapStream.write(buff, 0, rc);  
        }  
        byte[] in2b = swapStream.toByteArray();  
        return in2b;  
    }  
  
}

疑问1:为什么输入流,需要一小段一小段地读,而不是整段读取?
分析:如果需要整段读取,则需要取输入流的available(),但是该方法不能正确地返回输入流的总长度。

疑问2:为什么输入流的available()不能返回总长度?
分析:查看available方法的源码。返回值 描述是下面这个玩意,
* @return     an estimate of the number of bytes that can be read (or skipped
* over) from this input stream without blocking or {@code 0} when
* it reaches the end of the input stream.
大意就是 这个值是个估算的值,在读取流的过程中,没有发生阻塞时能够读取到的长度。
所以可以理解为在网络中读取时,可能会发生阻塞的情况。而在本地读取时,则能保证流的不阻塞传输。
建议不使用该办法获取流的字节数组总长度。
原文地址:https://www.cnblogs.com/chenjfblog/p/8915679.html