Convert InputStream to byte array in Java

前端 未结 30 3491
無奈伤痛
無奈伤痛 2020-11-21 12:08

How do I read an entire InputStream into a byte array?

30条回答
  •  一向
    一向 (楼主)
    2020-11-21 12:41

    The other case to get correct byte array via stream, after send request to server and waiting for the response.

    /**
             * Begin setup TCP connection to PC app
             * to open integrate connection between mobile app and pc app (or mobile app)
             */
            mSocket = new Socket(IP, port);
           // mSocket.setSoTimeout(30000);
    
            DataOutputStream mDos = new DataOutputStream(mSocket.getOutputStream());
    
            String str = "MobileRequest#" + params[0] + "#";
    
            mDos.write(str.getBytes());
    
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
    
            /* Since data are accepted as byte, all of them will be collected in the
            following byte array which initialised with accepted data length. */
            DataInputStream mDis = new DataInputStream(mSocket.getInputStream());
            byte[] data = new byte[mDis.available()];
    
            // Collecting data into byte array
            for (int i = 0; i < data.length; i++)
                data[i] = mDis.readByte();
    
            // Converting collected data in byte array into String.
            String RESPONSE = new String(data);
    

提交回复
热议问题