我尝试使用nio读取仅包含5个字符的小文本,但是fileChannel.read循环永远不会结束。
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);
}
}
}
答案 0 :(得分:1)
问题是您忘记在内部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");
}