zoukankan      html  css  js  c++  java
  • java读取输入流

    java读取输入流两种

        private static byte[] readStream(InputStream in){
            if(in==null){
                return null;
            }
            
            byte[] buffer = null;
            
            try {
                
                int availableLength = 0;
                while(availableLength==0){
                    availableLength = in.available();//可获取的字节流长度
                    
                    if(availableLength==0&&in.read()==-1){//防止读取流返回为空造成死循环
                        break;
                    }
                }
                
                buffer = new byte[availableLength];
                
                int readCount = 0;
                while(readCount<availableLength){
                    readCount += in.read(buffer, readCount, availableLength-readCount);
                }
                
            } catch (IOException e) {
                e.printStackTrace();
            } finally{
                if(in!=null){
                    try {
                        in.close();
                        in = null;
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                
            }
            
            return buffer;
        }
        
        
        public static byte[] readStream1(InputStream in) {
            
            byte[] b = null;
            ByteArrayOutputStream outSteam = null;
            try {
                byte[] buffer = new byte[1024 * 4];
                outSteam = new ByteArrayOutputStream();
                
                int len = -1; 
                while ((len = in.read(buffer)) != -1) {
                    outSteam.write(buffer, 0, len);
                }
                
                b = outSteam.toByteArray();
            } catch (IOException e) {
                e.printStackTrace();
            } finally{
                try {
                    if(outSteam!=null){
                        outSteam.close();
                        outSteam = null;
                    }
                    if(in!=null){
                        in.close();
                        in = null;
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return b;  
        }  
  • 相关阅读:
    Swift的函数与函数指针、闭包Closure等相关内容介绍
    spring+dubbo整合
    常用设计模式-适配器模式
    常用设计模式-工厂模式
    java动态代理
    程序对关系型数据库批量操作
    springboot整合mybatis
    JAVA代码实现多级树结构封装对象
    springboot集成redis缓存
    springboot入门
  • 原文地址:https://www.cnblogs.com/jinzhiming/p/6145074.html
Copyright © 2011-2022 走看看