从缓冲区

时间:2017-11-13 05:34:49

标签: java android bluetooth runtime-error indexoutofboundsexception

我的应用通过蓝牙将数据(字符串或字节)发送到另一个应用副本。 我尝试发送大文本或字节[]并得到此错误:

FATAL EXCEPTION: Thread-8297
        java.lang.ArrayIndexOutOfBoundsException: length=1024; index=1024
            at com.ramimartin.multibluetooth.bluetooth.BluetoothRunnable.run(BluetoothRunnable.java:147)
            at java.lang.Thread.run(Thread.java:841)

那么,为什么? 行代码

  

BluetoothRunnable.java:147

是:

while(bytesRead == bufferSize && buffer[bufferSize] != 0) {

完整代码:

        int bufferSize = 1024;
        int bytesRead;
        byte[] buffer = new byte[bufferSize];
                    try {
                        if(this.mInputStream != null) {
                            bytesRead = this.mInputStream.read(buffer);
                            ByteBuffer bbuf = ByteBuffer.allocate(bytesRead);
                            if(bytesRead != -1) {
                                while(bytesRead == bufferSize && buffer[bufferSize] != 0) {
                                    bbuf.put(buffer, 0, bytesRead);
                                    if(this.mInputStream == null) {
                                        return;
                                    }

                                    bytesRead = this.mInputStream.read(buffer);
                                }

                                bbuf.put(buffer, 0, bytesRead);
                            }

                            EventBus.getDefault().post(new BluetoothCommunicatorBytes(bbuf.array()));
                            continue;
                        }
                    } catch (IOException var8) {
                        Log.e(TAG, "===> Error Received Bytes IOException  : " + var8.getMessage());
                        continue;
                    }

1 个答案:

答案 0 :(得分:0)

这应该是:

while(bytesRead == bufferSize && buffer[bufferSize - 1] != 0)

也可能有时bufferSize不是1。

读取数组的方法是:

int arr[] = new int[10];

上述情况中的最大索引为:

arr[9]

索引从0开始。