Skip to Main Content

Java Programming

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

FileReader how to detect EOF

807605Aug 26 2007 — edited Aug 26 2007
Hi all,

I was going over some sample programs and i ran into a problem with the following program.
The problem is that it keeps counting the next character and incrementing instead of ending when the last line in the text file has no linebreak.
I guess it doesnt recognize that it has reached the EOF. Is there any way to fix this?
   
 public static void main(String[] args)
                   throws FileNotFoundException, IOException
   {
        int lineCount = 0;
        int[] letterCount = new int[26];

        IntClass next = new IntClass();

        FileReader inputStream = new FileReader("test.txt");

        PrintWriter outfile = new PrintWriter("textCh.out");

        next.setNum(inputStream.read());

        while (next.getNum() != -1)
        {
            copyText(inputStream, outfile, next, letterCount);
            lineCount++;
            next.setNum(inputStream.read());
        }  //end while loop

        writeTotal(outfile, lineCount, letterCount);

        outfile.close();
    }


 static void copyText(FileReader infile, PrintWriter outfile,
                         IntClass next, int[] letterC)
                         throws IOException
    {


        while (next.getNum() != (int)'\n')
        {
            outfile.print((char)(next.getNum()));
            chCount((char)(next.getNum()), letterC);
            next.setNum(infile.read());
        }

        outfile.println();
    }
Take care

Message was edited by:
RainX
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Sep 23 2007
Added on Aug 26 2007
18 comments
2,152 views