问题是,你忘记重置缓冲区的限制和位置后,内
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");
}