• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

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

 
Ranch Hand
Posts: 251
Hibernate Spring Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
please anyone tell me how we can find out end of file character from readChar() method in DataInputstream class.
 
Sheriff
Posts: 22784
131
Eclipse IDE Spring VI Editor Chrome Java Windows
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
reply
    Bookmark Topic Watch Topic
  • New Topic