0

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?

user3495562
  • 335
  • 1
  • 4
  • 16

2 Answers2

2

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.

user207421
  • 305,947
  • 44
  • 307
  • 483
  • @SotiriosDelimanolis I don't need to be more specific when every `read()` method in the JDK does the same thing. – user207421 Apr 11 '14 at 04:39
  • I have make my questions more specific – user3495562 Apr 11 '14 at 04:50
  • @Sotirios As every `read()` method in the JDK returns -1 at end of stream I consider your suggestion to be a complete waste of time, and indeed counterproductive. There's a reason they all behave they same way. It's called 'design'. You only have to learn it once. Not once per `FileChannel` and again per `FileReader,` which incidentally wasn't mentioned in the question, and again per `SocketChannel,` `BufferedReader,` `PushbackInputStream,` etc. etc. etc. Frankly your suggestion is ridiculous. – user207421 Apr 11 '14 at 04:53
  • @SotiriosDelimanolis Alternatively you could just have assumed that I was answering the question in the context of `FileChannel,` which *was* mentioned in the question, which only has three `read()` methods, all three of which behave as described. – user207421 Apr 11 '14 at 04:55
  • @SotiriosDelimanolis I'm baffled by the thought process that asks me 'which read() method is that?' because it wants me to say 'it applies to every read method in the JDK'. Try making yourself clear, or should I say 'explicit', next time. – user207421 Nov 27 '14 at 06:18
  • 1
    Yes, I misspelt your name. I think you should delete some of this nonsense, given that you eventually accepted 'Every read() method in the JDK'. I still don't understand why I had to explain it several times first. – user207421 Nov 27 '14 at 06:27
1

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
}
CHOCKO
  • 109
  • 4