BenEleven
BenEleven

Reputation: 57

java bufferedreader in combination with ready(), read() does not return -1

I have the following which sleeps after reading everything:

       while (true){
            if(reader.ready()){
                int intVal = reader.read();
                log.info("char: "+intVal);
                if(intVal == -1){
                    break;
                }
                char character = (char) intVal;
                line.append(character);
            }else{
                try {
                    log.info("sleeping");
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            long elapsedSeconds = watch.getTime(TimeUnit.SECONDS);
            if(elapsedSeconds > maxTimeToExecuteCommand){
                log.error("max read time elapsed.");
                break;
            }
        }

output is like:

char: 65
char: 66
char: 67
sleeping
sleeping
sleeping
....
....
goes on till elapsedSeconds is reached

the problem being intVal never gets a -1 which is weird.

whereas doing

        List<String> fullConsoleOutput = reader.lines()
                .collect(Collectors.toList());

works perfectly.

I do know about setting a timeout on a socket instead of doing this whole loop thing, but opening and closing a socket multiple times is not an option.

Upvotes: 1

Views: 44

Answers (1)

Joop Eggen
Joop Eggen

Reputation: 109547

public int read() throws IOException

Reads a single character. This method will block until a character is available, an I/O error occurs, or the end of the stream is reached.

So having read the last char, before seeing the end-of-file, -1, it blocks on reading, ready() giving false, till -1 would have been read. Another term in I/O code would be available() what would have been a better term for this behaviour.

You might try to read part of an char array (length 1), maybe getting 0 read at the end.

P.S.

My explanation is not realy that convincing.

Upvotes: 1

Related Questions