wood burning stoves 2.0*
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

Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
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

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

Joined: Oct 27, 2005
Posts: 19649

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.

How To Ask Questions How To Answer Questions
I agree. Here's the link: http://aspose.com/file-tools
subject: how we can detect end of file from readChar() method
Similar Threads
TextIO class - Matter copied from unrelated thread
Difference between System.in.read() and BufferedReader.read()
Range class