Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java ignores EOF while reading chars from file

Tags:

java

I try to read a File char by char. Unfortunately Java ignores EOF while reading chars from file.

FileReader fileReader = new FileReader(fileText);
char c;
String word = "";
List<String> words = new ArrayList<String>();

while ((c = (char) fileReader.read()) != -1) {
    System.out.println(c);
    if (c != ' ') {
        word = word + c;
    }
    else {
        words.add(word + " ");
        word = "";
    }
}

It should break up after the file is read, but instead it never stops running....

like image 230
Fendrix Avatar asked Jul 25 '26 00:07

Fendrix


1 Answers

In Java, char is unsigned and cannot equal -1. You should do the comparison before you do the cast.

int ch;
while ((ch = fileReader.read()) != -1) {
    char c = (char)ch;
    System.out.println(c);
    ...
}
like image 129
NPE Avatar answered Jul 26 '26 17:07

NPE



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!