Java — How to read an unknown number of bytes from an inputStream (socket/socketServer)?

后端 未结 11 1027
梦如初夏
梦如初夏 2020-12-15 07:42

Looking to read in some bytes over a socket using an inputStream. The bytes sent by the server may be of variable quantity, and the client doesn\'t know in advance the lengt

11条回答
  •  盖世英雄少女心
    2020-12-15 08:33

    Stream all Input data into Output stream. Here is working example:

        InputStream inputStream = null;
        byte[] tempStorage = new byte[1024];//try to read 1Kb at time
        int bLength;
        try{
    
            ByteArrayOutputStream outputByteArrayStream =  new ByteArrayOutputStream();     
            if (fileName.startsWith("http"))
                inputStream = new URL(fileName).openStream();
            else
                inputStream = new FileInputStream(fileName);            
    
            while ((bLength = inputStream.read(tempStorage)) != -1) {
                    outputByteArrayStream.write(tempStorage, 0, bLength);
            }
            outputByteArrayStream.flush();
            //Here is the byte array at the end
            byte[] finalByteArray = outputByteArrayStream.toByteArray();
            outputByteArrayStream.close();
            inputStream.close();
        }catch(Exception e){
            e.printStackTrace();
            if (inputStream != null) inputStream.close();
        }
    

提交回复
热议问题