代码之家  ›  专栏  ›  技术社区  ›  HongyanShen

为什么是文件通道.read循环永不结束?

  •  1
  • HongyanShen  · 技术社区  · 6 年前

    我尝试使用nio来阅读一个只有5个字符的小文本,但是文件通道.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 回复  |  直到 6 年前
        1
  •  1
  •   Lolo    6 年前

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