gpt4 book ai didi

java - ReadableByteChannel.read() 的行为

转载 作者:行者123 更新时间:2023-12-01 14:50:55 25 4
gpt4 key购买 nike

如果在读取操作期间或后续调用中达到 EOF,read() 是否返回 -1? Java 文档对此并不完全清楚,我正在阅读的书也没有完全清楚。

书中的以下代码正在读取一个文件,该文件包含三种不同类型的重复值: double 值、不同长度的字符串和二进制长值。缓冲区应该填充在任何值中间的某个随机位置,并且代码将处理它。我不明白的是,如果在读取操作期间返回 -1,最后的值将不会在 prinf 语句中输出。

    try(ReadableByteChannel inCh = Files.newByteChannel(file)) {

ByteBuffer buf = ByteBuffer.allocateDirect(256);
buf.position(buf.limit());
int strLength = 0;
byte[] strChars = null;

while(true) {
if(buf.remaining() < 8) {
if(inCh.read(buf.compact()) == -1) {
break;
}
buf.flip();
}
strLength = (int)buf.getDouble();

if (buf.remaining() < 2*strLength) {
if(inCh.read(buf.compact()) == -1) {
System.err.println("EOF found while reading the prime string.");
break;
}
buf.flip();
}
strChars = new byte[2*strLength];
buf.get(strChars);

if(buf.remaining() <8) {
if(inCh.read(buf.compact()) == -1) {
System.err.println("EOF found reading the binary prime value.");
break;
}
buf.flip();
}
System.out.printf("String length: %3s String: %-12s Binary Value: %3d%n",
strLength, ByteBuffer.wrap(strChars).asCharBuffer(), buf.getLong());
}
System.out.println("\n EOF Reached.");

最佳答案

我建议做一个简单的测试来了解它是如何工作的,就像这样

    ReadableByteChannel in = Files.newByteChannel(Paths.get("1.txt"));
ByteBuffer b = ByteBuffer.allocate(100);
System.out.println(in.read(b));
System.out.println(in.read(b));

1.txt包含1个字节,测试打印

1
-1

关于java - ReadableByteChannel.read() 的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14866045/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com