Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/oop/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 为什么fileChannel.read循环永远不会结束?_Java_Nio_Filechannel - Fatal编程技术网

Java 为什么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

我尝试使用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);
            }
        }
    }

问题是,在内部
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");
}