0

このコードの何が問題になっていますか? :

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

最後の行は常に BufferUnderflowException をスローします。変数 bytesCount には 4 が含まれます。

ここで何が恋しいですか?

4

2 に答える 2

5

絶対取得を使用するか、読み取る前にバッファーを巻き戻します。

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

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

ドキュメントはすぐにはわかりませんが( ReadableByteChannel.read()に到達するまでリンクをクリックする必要があります)、バッファーへの読み取りはバッファーの位置を変更します。

于 2013-06-21T20:29:23.960 に答える
0

get() または write() を使用してバッファからデータを取得する前に、バッファを flip() する必要があります。

于 2013-06-21T23:37:15.593 に答える