Reputation: 335
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?
Upvotes: 0
Views: 2451
Reputation: 310913
If the int
returned by the read()
method is -1 you have reached the end of the file.
EDIT Re your edit, the value returned by the read()
method is a count.
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.
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.
If you call buffer.clear()
after the first read()
, the next read()
will return -1.
Upvotes: 2
Reputation: 109
If the int returned by reader is -1 then you have reached to end of file.
for example:-
Reader reader = new FileReader("yourfilename");
int data = reader.read();
if(data != -1){
// your code
}
Upvotes: 1