为什么fileChannel.read循环永远不会结束?

时间:2018-09-09 03:59:26

标签: 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);
        ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
        while (fileChannel.read(byteBuffer) != -1) {
            byteBuffer.flip();
            while (byteBuffer.hasRemaining()) {
                char c = (char)byteBuffer.get();
                System.out.println(c);
            }
        }
    }

1 个答案:

答案 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");
}