簡體   English   中英

如何使用NIO從文件讀取Integer而不獲取BufferUnderflowException?

[英]How to read Integer from a file with NIO and not to get BufferUnderflowException?

此代碼有什么問題?

ByteBuffer byteBuffer = ByteBuffer.allocate(4);
FileChannel channel = cacheFile.getChannel();
int bytesCount = channel.read(byteBuffer, offset);
int value = byteBuffer.getInt();

最后一行總是拋出BufferUnderflowException。 變量bytesCount包含4。

我在這里想念什么?

在讀取之前,請使用絕對get或倒帶緩沖區:

// option 1
int value = byteBuffer.getInt(0);

// option 2
buffer.rewind();
int value = byteBuffer.getInt();

盡管文檔不是立即顯而易見的(您必須單擊鏈接,直到到達ReadableByteChannel.read() ),但讀入緩沖區會更改緩沖區的位置。

您必須先翻轉()緩沖區,然后再使用get()或write()從緩沖區中取出數據。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM