【问题标题】:ArrayIndexOutOfBoundsException when read from buffer [duplicate]从缓冲区读取时出现 ArrayIndexOutOfBoundsException [重复]
【发布时间】:2018-04-25 17:49:05
【问题描述】:

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

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;
                    }

【问题讨论】:

  • Java 中的数组是 0 索引的。

标签: java android bluetooth runtime-error indexoutofboundsexception


【解决方案1】:

这应该是:

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

有时bufferSize可能会大于1。

而读取数组的方式是:

int arr[] = new int[10];

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

arr[9]

因为索引从 0 开始。

【讨论】:

  • 好的,我现在试试
  • 所以,我尝试了您的示例,但现在在代码“bbuf.put(buffer, 0, bytesRead);”处出现错误“java.nio.BufferOverflowException”。我需要将 bufferSize 设置为更大的 int?
  • 问题已解决。
猜你喜欢
  • 1970-01-01
  • 2012-03-15
  • 1970-01-01
  • 2016-06-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多