gpt4 book ai didi

java - 为什么 FileChannel 读取永远不会结束?

转载 作者:行者123 更新时间:2023-11-29 03:01:10 29 4
gpt4 key购买 nike

当我执行以下类(class)时

import java.io.*;
import java.nio.*;
import java.nio.file.*;
import java.nio.channels.*;

public class FileChannelTest {
public static void main(final String... args) throws IOException {
final File file = File.createTempFile("temp", null);
file.deleteOnExit();
// write some
try(OutputStream output = new FileOutputStream(file)) {
output.write(new byte[128]);
output.flush();
}
System.out.println("length: " + file.length());
// read to end
try(FileChannel channel
= FileChannel.open(file.toPath(), StandardOpenOption.READ)) {
final ByteBuffer buffer = ByteBuffer.allocate(128);
for(int read; (read = channel.read(buffer)) != -1; ) {
System.out.println("read: " + read);
}
}
}
}

阅读循环永无止境。

$ java -version
java version "1.8.0_65"
Java(TM) SE Runtime Environment (build 1.8.0_65-b17)
Java HotSpot(TM) 64-Bit Server VM (build 25.65-b01, mixed mode)
$ java FileChannelTest.java
$ java FileChannelTest
length: 128
read: 128
read: 0
read: 0
read: 0
...
...
...

FileChannel.read(ByteBuffer)说,

Reads a sequence of bytes from this channel into the given buffer. Bytes are read starting at this channel's current file position, and then the file position is updated with the number of bytes actually read. Otherwise this method behaves exactly as specified in the ReadableByteChannel interface.

否则是什么意思?

最佳答案

当您读入 ByteBuffer 时,它只能读取缓冲区中可用的字节数,即 byteBuffer.remaining() 这意味着一旦缓冲区已满,当您读取它时返回 0

如果您已经消耗了所有读取的数据,我建议您使用 clear(),如果您只消耗了一部分读取的数据,我建议您使用 compact()

      for(int read; (read = channel.read(buffer)) != -1; ) {                                                                                  
System.out.println("read: " + read);
buffer.clear(); // so we can read more data
}

关于java - 为什么 FileChannel 读取永远不会结束?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34817945/

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