File Reader not working properly?

I have the following code and for some reason the end of file is never reached so the while loop never does end.

public class Temp {
FileReader fr;

Temp() {
    try {
        fr = new FileReader("File path");
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }
}

public static void main(String[] args) {
    Temp ob = new Temp();

    try {
        char c;
        while ((c = (char) ob.fr.read()) != -1) {
            System.out.println(c);
        }
        ob.fr.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

Can any one help me solve this !? thanks in advance :)

Jon Skeet
people
quotationmark

You're comparing c - a char, which is an unsigned type - with -1. Don't do that. It's promoting c to int, so you'll end up with 65535 instead. Instead, make c an int and do the cast to char inside the body of the loop.

int c;
while ((c = ob.fr.read()) != -1) {
    System.out.println((char) c);
}

I'd also advise against creating a new object just for the sake of storing something in a variable... you could have used a local variable for the FileReader here.

I'd also advise:

  • Not just continuing if an exception is thrown, as if nothing had gone wrong
  • Using try-with-resources instead of manually closing the reader
  • Avoiding FileReader to start with as it always uses the default encoding. (Use a FileInputStream with an InputStreamReader, or from Java 7 just use Files.newBufferedReader.)

people

See more on this question at Stackoverflow