Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

how we can detect end of file from readChar() method

 
Thakur Sachin Singh
Ranch Hand
Posts: 248
Hibernate Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
please anyone tell me how we can find out end of file character from readChar() method in DataInputstream class.
 
Rob Spoor
Sheriff
Pie
Posts: 20510
54
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You can't. Well, not directly. Most of the reading methods from DataInputStream assume there are enough bytes available to return the data. The only differences are read(), read(byte[]), read(byte[], int, int) and readLine(). The first three return -1 when there is no data, the latter returns null.

Now I said not directly. That's because all the other methods throw an EOFException to indicate that the end of the file was reached. You can catch that and then stop when this occurs.

Another option is to use a BufferedInputStream wrapped inside the DataInputStream. That way you can use the mark(int) and reset() methods:
This last way is the safest because catching the EOFException will still have read (and consumed) one byte if there is only one available.

Still, DataInputStream should be used only when you know what there is. After all, if you try to read a char while there is something different (perhaps a long) then you will get strange results. If you have written a number of chars before and now you want to read them all then you should change the file structure: first write an int with the number of chars to write, then write that many chars. The reading will then first read that int, and then read just as many chars.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic