Can I peek on a BufferedReader?

后端 未结 8 1786
别跟我提以往
别跟我提以往 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:17

    You can use a PushbackReader. Using that you can read a character, then unread it. This essentially allows you to push it back.

    PushbackReader pr = new PushbackReader(reader);
    char c = (char)pr.read();
    // do something to look at c
    pr.unread((int)c); //pushes the character back into the buffer
    
    0 讨论(0)
  • 2021-01-01 14:22

    The answer from pgmura (relying on the ready() method) is simple and works. But bear in mind that it's because Sun's implementation of the method; which does not really agree with the documentation. I would not rely on that, if this behaviour is critical. See here http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4090471 I'd rather go with the PushbackReader option.

    0 讨论(0)
  • 2021-01-01 14:27

    You could use a PushBackReader to read a character, and then "push it back". That way you know for sure that something was there, without affecting its overall state - a "peek".

    0 讨论(0)
  • 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();
        // ...
    }
    
    0 讨论(0)
  • 2021-01-01 14:32

    You can try the "boolean ready()" method. From the Java 6 API doc: "A buffered character stream is ready if the buffer is not empty, or if the underlying character stream is ready."

    BufferedReader r = new BufferedReader(reader);
    if(r.ready())
    {
       r.read();
    }
    
    0 讨论(0)
  • 2021-01-01 14:32

    The following code will look at the first byte in the Stream. Should act as a peek for you.

    BufferedReader bReader = new BufferedReader(inputStream);
    bReader.mark(1);
    int byte1 = bReader.read();
    bReader.reset();
    
    0 讨论(0)
提交回复
热议问题