zoukankan      html  css  js  c++  java
  • 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.
    大意就是 这个值是个估算的值,在读取流的过程中,没有发生阻塞时能够读取到的长度。
    所以可以理解为在网络中读取时,可能会发生阻塞的情况。而在本地读取时,则能保证流的不阻塞传输。
    建议不使用该办法获取流的字节数组总长度。
  • 相关阅读:
    矩阵分析及其在线性代数中的应用(3-4)
    矩阵分析及其在线性代数中的应用(1-2)
    信息检索的评价标准
    Converting Between Image Classes (matlab 中图像类之间的转换)
    Ubuntu 14.04,root the Nexus 7 (2013).
    ACM进阶计划
    matlab R2012a in ubuntu12.04
    人,绩效和职业道德
    运行及总结
    仓库管理 测试计划
  • 原文地址:https://www.cnblogs.com/chenjfblog/p/8915679.html
Copyright © 2011-2022 走看看