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

时间:2015-08-23 09:35:11

标签: java android inputstream

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

我正在读取IR信号并将其从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();
            }
        }
    }

1 个答案:

答案 0 :(得分:2)

编辑:

我的旧答案是错误的,请参阅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);

此读取方法尝试读取缓冲区中剩余空间的字节数。如果流在缓冲区完全填满之前结束,则返回实际读取的字节数。请参阅JavaDoc

相关问题