Can I peek on a BufferedReader?

后端 未结 8 1840
别跟我提以往
别跟我提以往 2021-01-01 14:02

Is there a way to check if in BufferedReader object is something to read? Something like C++ cin.peek(). Thanks.

8条回答
  •  一向
    一向 (楼主)
    2021-01-01 14:29

    The normal idiom is to check in a loop if BufferedReader#readLine() doesn't return null. If end of stream is reached (e.g. end of file, socket closed, etc), then it returns null.

    E.g.

    BufferedReader reader = new BufferedReader(someReaderSource);
    String line = null;
    while ((line = reader.readLine()) != null) {
        // ...
    }
    

    If you don't want to read in lines (which is by the way the major reason a BufferedReader is been chosen), then use BufferedReader#ready() instead:

    BufferedReader reader = new BufferedReader(someReaderSource);
    while (reader.ready()) {
        int data = reader.read();
        // ...
    }
    

提交回复
热议问题