readChar() method and EOF exception

I am a CS major and am trying to improve on my programming skills, but I have come across a roadblock. I am using the readChar() method to read characters one by one from a specified file and almost everything is going smoothly except that I am not sure on the most efficient way to let my program know it has reached the end of a file. I am trying to use the End Of File execption, but it still reads on forever. I pasted my code here for an illustration. Any pointers?

- Alex


public class FileDemo {
    public static void main(String[] args) throws IOException {

     if (args.length < 1){
         System.out.println("Program syntax: java FileDemo FILE.XXX");

     DataInputStream in = new DataInputStream(
                          new FileInputStream(args[0]));

     InputStreamReader isr = new InputStreamReader(in);

     System.out.println("<<Start of file>>");

     try {
         char newChar = (char);
         while(true) {
          newChar = (char);
     } catch (EOFException e) { }
     System.out.println("<<End of file>>");    
Who is Participating?
m_onkey_boyConnect With a Mentor Commented:
int c;
while ((c = != -1) {
BTW - in your example, DataInputStream is not adding anything to your program other than overhead.
alrav79Author Commented:
what do you mean overhead?
Never miss a deadline with

The revolutionary project management tool is here!   Plan visually with a single glance and make sure your projects get done.

alrav79Author Commented:
could have explained the process a litte more
You didn't give me a chance to elaborate - you could have asked.


What I meant by overhead was that by using the datainputstream, you have instantiated an object tha was not needed.  Also, each call to read() is being passed up an extra method call ( calls, which in turn calls  Why not cut out the middleman?

As far as explaining the process - the code is self-explanatory.  I guess the part you should notice is that -1 is the EOF marker in a Java stream.
alrav79Author Commented:
sorry, man, that was my fault....thanks for the explanation though; it was very helpful
All Courses

From novice to tech pro — start learning today.