解决方案 »

  1.   

    ByteArrayOutputStream 有缓冲区,上面那种写法没有
      

  2.   

    第一种写法对吗?   这种能得到InputStream输入流的所有字节并返回吗? 
      

  3.   

    一般带缓冲区的记得最好调用flush(),要不内容有可能读不出来
      

  4.   

    你把buffer改大就能看出问题了。  byte[] buffer = new byte[1024 * 1024];   再用这个buffer来读你输入的6个字符。 一般程序设置的buffer都是固定大小的,不会根据你输入的数据大小再去设定buffer, 那么很容易出现buffer读不满的情况,第二总写法就适用了
      

  5.   

    第二种是不是要把if换成while,就可以保证数据全部从流中读出
      

  6.   

    如果要真正的和第二种的写法返回一样的结果,则第一种写法应该类似这样的public class StreamTool {
        
        public static byte[] readInputStream(InputStream inputStream)
                throws Exception {
            int bigLen = 1024;
            byte[] maxBuffer = new byte[bigLen];
            byte[] buffer = new byte[8];
     
            // ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            int length = -1;
            int totalLen = 0;
            if ((length = inputStream.read(buffer)) != -1) {
                if(totalLen + length > bigLen){
                    bigLen += 512;
                    byte[] temp = new byte[bigLen];
                    System.arraycopy(maxBuffer, 0, temp, 0, totalLen);
                    maxBuffer = temp;
                }
                System.arraycopy(buffer, 0, maxBuffer, totalLen, length);
                totalLen +=length;
            }
             
            return maxBuffer;
        }
    }如果需要读取的字节很多,就要不断的扩充数组,并拷贝数据,性能上会有很多影响
      

  7.   

    第二种需要把if改成while吧。
    恩,手误 都要改成while