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

后端 未结 11 1013
梦如初夏
梦如初夏 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:31

    Without re-inventing the wheel, using Apache Commons:

    IOUtils.toByteArray(inputStream);
    

    For example, complete code with error handling:

        public static byte[] readInputStreamToByteArray(InputStream inputStream) {
        if (inputStream == null) {
            // normally, the caller should check for null after getting the InputStream object from a resource
            throw new FileProcessingException("Cannot read from InputStream that is NULL. The resource requested by the caller may not exist or was not looked up correctly.");
        }
        try {
            return IOUtils.toByteArray(inputStream);
        } catch (IOException e) {
            throw new FileProcessingException("Error reading input stream.", e);
        } finally {
            closeStream(inputStream);
        }
    }
    
    private static void closeStream(Closeable closeable) {
        try {
            if (closeable != null) {
                closeable.close();
            }
        } catch (Exception e) {
            throw new FileProcessingException("IO Error closing a stream.", e);
        }
    }
    

    Where FileProcessingException is your app-specific meaningful RT exception that will travel uninterrupted to your proper handler w/o polluting the code in between.

提交回复
热议问题