简体   繁体   English

使用ByteBuffer和FileChannel结束文件

[英]End of file using ByteBuffer and FileChannel

I write a small code, say 我写一个小代码,说

ByteBuffer buffer = ByteBuffer.allocate(10);
int w= fc.read(buffer);
System.out.println(w);
w= fc.read(buffer);
System.out.println(w);
w= fc.read(buffer);
System.out.println(w);

say the file contains 10 bytes, the result appeared on the screen is 10, 0, 0, but no -1 appers as the end of the file, why? 假设文件包含10个字节,屏幕上出现的结果是10、0、0,但文件末尾没有-1,为什么?

If the int returned by the read() method is -1 you have reached the end of the file. 如果read()方法返回的int为-1,则您已到达文件末尾。

EDIT Re your edit, the value returned by the read() method is a count. EDIT重新进行编辑, read()方法返回的值是一个计数。

The first time, you read 10 bytes, and the buffer's capacity was 10 bytes, so you (a) printed 10 and (b) filled the buffer. 第一次读取10个字节,缓冲区的容量为10个字节,因此(a)打印10 ,(b)填充缓冲区。

All the other times, the buffer was already full, because you didn't clear() it, so nothing was read and zero was returned, so you printed zero. 其他所有时间,缓冲区已经满了,因为您没有将它clear() ,所以什么也不读取,返回零,所以您打印了零。

If you call buffer.clear() after the first read() , the next read() will return -1. 如果在第一个read() buffer.clear()之后调用buffer.clear() ,则下一个read()将返回-1。

If the int returned by reader is -1 then you have reached to end of file. 如果阅读器返回的int为-1​​,则您已到达文件末尾。

for example:- 例如:-

Reader reader = new FileReader("yourfilename");

int data = reader.read();

if(data != -1){
 // your code
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM