Receive byte[] using ByteArrayInputStream from a socket

后端 未结 2 1713
感动是毒
感动是毒 2021-01-02 06:56

Here is the code but got error:

bin = new ByteArrayInputStream(socket.getInputStream());

Is it possible to receive byte[] usin

2条回答
  •  我在风中等你
    2021-01-02 07:21

    You can't get an instance of ByteArrayInputStream by reading directly from socket.
    You require to read first and find byte content.
    Then use it to create an instance of ByteArrayInputStream.

    InputStream inputStream = socket.getInputStream();  
    
    // read from the stream  
    ByteArrayOutputStream baos = new ByteArrayOutputStream();  
    byte[] content = new byte[ 2048 ];  
    int bytesRead = -1;  
    while( ( bytesRead = inputStream.read( content ) ) != -1 ) {  
        baos.write( content, 0, bytesRead );  
    } // while  
    

    Now, as you have baos in hand, I don't think you still need a bais instance.
    But, to make it complete,
    you can generate byte array input stream as below

    ByteArrayInputStream bais = new ByteArrayInputStream( baos.toByteArray() );  
    

提交回复
热议问题