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>>");    
    }
}
alrav79Asked:
Who is Participating?
 
m_onkey_boyConnect With a Mentor Commented:
int c;
while ((c = isr.read()) != -1) {
  System.out.println((char)c);
}
0
 
m_onkey_boyCommented:
BTW - in your example, DataInputStream is not adding anything to your program other than overhead.
0
 
alrav79Author Commented:
what do you mean overhead?
0
Never miss a deadline with monday.com

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
0
 
m_onkey_boyCommented:
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.
0
 
alrav79Author Commented:
sorry, man, that was my fault....thanks for the explanation though; it was very helpful
0
All Courses

From novice to tech pro — start learning today.