Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/sockets/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何使用NIO从文件中读取整数,而不获取BufferUnderflowException?_Java_Nio - Fatal编程技术网

Java 如何使用NIO从文件中读取整数,而不获取BufferUnderflowException?

Java 如何使用NIO从文件中读取整数,而不获取BufferUnderflowException?,java,nio,Java,Nio,这个代码怎么了 ByteBuffer byteBuffer = ByteBuffer.allocate(4); FileChannel channel = cacheFile.getChannel(); int bytesCount = channel.read(byteBuffer, offset); int value = byteBuffer.getInt(); 最后一行总是抛出BufferUnderflowException。 变量bytesCount包含4 我在这里错过了什么?在读取

这个代码怎么了

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();

虽然文档不是立即可见的(您必须单击链接,直到找到为止),但读入缓冲区会更改缓冲区的位置。

在读取之前,请使用绝对获取或倒带缓冲区:

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

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

虽然文档不是立即可见的(在到达之前必须单击链接),但读入缓冲区会更改缓冲区的位置。

在使用get()或write()从缓冲区中取出数据之前,必须翻转()缓冲区。

在使用get()或write()从缓冲区中取出数据之前,必须翻转()缓冲区.

你能给我们展示一下完全编译的代码吗?@tieTYT:这里有一段更大的代码,可以读写@tieTYT:它的使用方式是:第一步调用sync(0),第二步调用getSolution(0,0)//getSolution在第1行中包含故意忽略缓存和使用NIO的错误。您能给我们展示完整编译的代码吗?@tieTYT:这里有一段更大的代码,用于读取和写入@tieTYT:下一种方式:第一步调用sync(0),第二步调用getSolution(0,0)//getSolution在第1行中包含故意忽略缓存并使用NIO的错误。