一次将所有 InputStream 值读入 byte[] 数组

Read all InputStream values at once into a byte[] array

有没有办法一次读取所有 InputStream 值而不需要使用一些 Apache IO lib

我正在读取红外信号并将其从 InputStream 保存到 byte[] 数组中。在调试时,我注意到它只有在我在那里放置延迟时才会起作用,这样我就可以一次读取所有字节然后进行处理。

有更聪明的方法吗?

代码:

 public void run() {
        Log.i(TAG, "BEGIN mConnectedThread");
        byte[] buffer = new byte[100];
        int numberOfBytes;
        removeSharedPrefs("mSharedPrefs");
        // Keep listening to the InputStream while connected
        while (true) {
            try {
                // Read from the InputStream
                numberOfBytes = mmInStream.read(buffer);
                Thread.sleep(700);  //If I stop it here for a while, all works fine, because array is fully populated
                if (numberOfBytes  > 90){
                    // GET AXIS VALUES FROM THE SHARED PREFS
                    String[] refValues = loadArray("gestureBuffer", context);
                    if (refValues!=null && refValues.length>90) {
                        int incorrectPoints;
                        if ((incorrectPoints = checkIfGesureIsSameAsPrevious(buffer, refValues, numberOfBytes)) < 5) {
                           //Correct
                        } else {
                           //Incorrect
                        }
                    }
                    saveArray(buffer, numberOfBytes);
                }else{
                    System.out.println("Transmission of the data was corrupted.");
                }
                buffer = new byte[100];
                // Send the obtained bytes to the UI Activity
                mHandler.obtainMessage(Constants.MESSAGE_READ, numberOfBytes, -1, buffer)
                        .sendToTarget();
            } catch (IOException e) {
                Log.e(TAG, "disconnected", e);
                connectionLost();
                // Start the service over to restart listening mode
                BluetoothChatService.this.start();
                break;
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

编辑:

我的老答案错了,看EJP评论!请不要使用它。 ByteChannels 的行为取决于 InputStreams 是否阻塞。

所以这就是我建议的原因,您只需从 Apache Commons 复制 IOUtils.read

public static int read(final InputStream input, final byte[] buffer) throws IOException {
    int remaining = buffer.length;
    while (remaining > 0) {
        final int location = buffer.length - remaining;
        final int count = input.read(buffer, location, remaining);
        if (count == -1) { // EOF
            break;
        }
        remaining -= count;
    }
    return buffer.length - remaining;
}

旧答案:

您可以使用 ByteChannels 并读入 ByteBuffer:

ReadableByteChannel c = Channels.newChannel(inputstream);
ByteBuffer buf = ByteBuffer.allocate(numBytesExpected);
int numBytesActuallyRead = c.read(buf);

此读取方法正在尝试读取与缓冲区中剩余 space 一样多的字节。如果流在缓冲区完全填满之前结束,则返回实际读取的字节数。参见 JavaDoc