为什么 fileChannel.read 循环永远不会结束?
Why the fileChannel.read loop never end?
我尝试使用 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()
捕获 return 值。在您的情况下,它会告诉您它正在连续 returning 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");
}
我尝试使用 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()
捕获 return 值。在您的情况下,它会告诉您它正在连续 returning 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");
}