Link to home
Start Free TrialLog in
Avatar of alrav79
alrav79

asked on

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


import java.io.*;

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

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

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

     InputStreamReader isr = new InputStreamReader(in);


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


     try {
         char newChar = (char) isr.read();
         while(true) {
          System.out.print(newChar);
          newChar = (char) isr.read();
         }
     } catch (EOFException e) { }
     in.close();
     
     System.out.println("<<End of file>>");    
    }
}
ASKER CERTIFIED SOLUTION
Avatar of m_onkey_boy
m_onkey_boy

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of m_onkey_boy
m_onkey_boy

BTW - in your example, DataInputStream is not adding anything to your program other than overhead.
Avatar of alrav79

ASKER

what do you mean overhead?
Avatar of alrav79

ASKER

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

OK:

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 (InputStreamReader.read() calls DataInputStream.read(), which in turn calls FileInputStream.read()).  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.
Avatar of alrav79

ASKER

sorry, man, that was my fault....thanks for the explanation though; it was very helpful