【问题标题】:ByteBuffer.get(byte[], int, int) failed on Android ICS and JBByteBuffer.get(byte[], int, int) 在 Android ICS 和 JB 上失败
【发布时间】:2015-02-07 13:37:46
【问题描述】:

Android Ice Cream Sandwitch 和 Jelly Bean 中的 ByteBuffer 实现存在奇怪的行为。问题是,get 方法会抛出 BufferUnderflowException。 Froyo、GingerBread、Kitkat 和 Lollipop 中没有。

    printAndRewind(byteBuffer);
    printAndRewind(byteBuffer);
    try {
        byteBuffer.get(tagIdentifier, 0, 3);
    } catch (BufferUnderflowException e) {
        logger.info("This will be printed in ICS & JB " + e);
        byteBuffer.rewind();
    } 

这是 printAndRewind 方法:

private void printAndRewind(ByteBuffer byteBuffer) {
    StringBuilder builder = new StringBuilder();
    while (byteBuffer.hasRemaining()) {
        builder.append(", ").append(byteBuffer.get());
    }
    logger.info(builder.toString());
    byteBuffer.rewind();
}

这是错误吗?如果是,那么如何克服这个问题?我有一个很大程度上依赖于 ByteBuffer 的库。谢谢

【问题讨论】:

  • 根据developer.android.com/reference/java/nio/…, int, int) 异常是byteCount > remaining()时的预期行为
  • 它是否回答了为什么 GingerBread 和 Froyo 不会出现问题??
  • 不,不需要。我的观点是,您的代码首先是错误的。如果你的代码没有按照规范行事,你就不能说是一个错误。当 byteBuffer 的可用字节少于 3 个时,您的代码如何知道实际复制到 tagIdentifier 的字节数?
  • 我不是编程的孩子。当然,我已经检查了前面的行。为简洁起见,我删除了检查代码。
  • 对给您带来的不便深表歉意:)

标签: android


【解决方案1】:

我相信java.nio.MappedByteBufferAdapter 类中存在错误,它是java.nio.ByteBuffer 的实现,仅在 ICS 和 JB 中发生。也许,在 Honeycomb 中也是如此。

所以,为了防止这个错误,不要使用这个类。

使用这个:

byteBuf =  ByteBuffer.allocate(startByte);
channel.read(byteBuf, 0);

代替:

inStream = new FileInputStream(file);
channel = inStream.getChannel();
byteBuf = channel.map(FileChannel.MapMode.READ_ONLY, 0, startByte);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-30
    • 2011-01-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多