Java 为什么fileChannel.read循环永远不会结束?
我尝试使用nio读取仅包含5个字符的小文本,但是fileChannel.read循环永远不会结束Java 为什么fileChannel.read循环永远不会结束?,java,nio,filechannel,Java,Nio,Filechannel,我尝试使用nio读取仅包含5个字符的小文本,但是fileChannel.read循环永远不会结束 public static void main(String[] args) throws IOException { FileChannel fileChannel = FileChannel.open(Paths.get("input.txt"), StandardOpenOption.READ, StandardOpenOption.WRITE); ByteBu
public static void main(String[] args) throws IOException {
FileChannel fileChannel = FileChannel.open(Paths.get("input.txt"), StandardOpenOption.READ, StandardOpenOption.WRITE);
ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
while (fileChannel.read(byteBuffer) != -1) {
byteBuffer.flip();
while (byteBuffer.hasRemaining()) {
char c = (char)byteBuffer.get();
System.out.println(c);
}
}
}
问题是,在内部
while
循环之后,您忘记重置缓冲区的限制和位置。读取前1024个字符后,缓冲区将满,每次尝试读取缓冲区时,将尝试读取最多remaining=limit-position
字节,即缓冲区满后读取0字节
此外,您应该始终从fileChannel.read()
捕获返回值。在您的情况下,它会告诉您它正在连续返回0
在内部循环解决问题后调用byteBuffer.clear()
:
public static void main(String[] args) throws IOException {
FileChannel fileChannel = FileChannel.open(Paths.get("JPPFConfiguration.txt"), StandardOpenOption.READ, StandardOpenOption.WRITE);
ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
int n;
long sum = 0L;
while ((n = fileChannel.read(byteBuffer)) != -1) {
sum += n;
byteBuffer.flip();
while (byteBuffer.hasRemaining()) {
char c = (char) byteBuffer.get();
System.out.print(c);
}
System.out.println("\n read " + n + " bytes");
byteBuffer.clear();
}
System.out.println("read " + sum + " bytes total");
}