This week's book giveaway is in the Mac OS forum.
We're giving away four copies of a choice of "Take Control of Upgrading to Yosemite" or "Take Control of Automating Your Mac" and have Joe Kissell on-line!
See this thread for details.
The moose likes I/O and Streams and the fly likes how we can detect end of file from readChar() method Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


JavaRanch » Java Forums » Java » I/O and Streams
Bookmark "how we can detect end of file from readChar() method" Watch "how we can detect end of file from readChar() method" New topic
Author

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

Thakur Sachin Singh
Ranch Hand

Joined: Jun 15, 2010
Posts: 232

please anyone tell me how we can find out end of file character from readChar() method in DataInputstream class.


SCJP 6- 91%, IBM DB2, IBM RAD Certified
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19697
    
  20

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.


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
 
GeeCON Prague 2014
 
subject: how we can detect end of file from readChar() method