How to determine the exact state of a BufferedReader?

后端 未结 8 1661
慢半拍i
慢半拍i 2020-12-17 00:21

I have a BufferedReader (generated by new BufferedReader(new InputStreamReader(process.getInputStream()))). I\'m quite new to the concept of a

8条回答
  •  情话喂你
    2020-12-17 00:40

    If you just want the timeout then the other methods here are possibly better. If you want a non-blocking buffered reader, here's how I would do it, with threads: (please note I haven't tested this and at the very least it needs some exception handling added)

    public class MyReader implements Runnable {
        private final BufferedReader reader;
        private ConcurrentLinkedQueue queue = new ConcurrentLinkedQueue();
        private boolean closed = false;
    
        public MyReader(BufferedReader reader) {
            this.reader = reader;
        }
    
        public void run() {
            String line;
            while((line = reader.readLine()) != null) {
                queue.add(line);
            }
            closed = true;
        }
    
        // Returns true iff there is at least one line on the queue
        public boolean ready() {
            return(queue.peek() != null);
        }
    
        // Returns true if the underlying connection has closed
        // Note that there may still be data on the queue!
        public boolean isClosed() {
            return closed;
        }
    
        // Get next line
        // Returns null if there is none
        // Never blocks
        public String readLine() {
            return(queue.poll());
        }
    }
    

    Here's how to use it:

    BufferedReader b; // Initialise however you normally do
    MyReader reader = new MyReader(b);
    new Thread(reader).start();
    
    // True if there is data to be read regardless of connection state
    reader.ready();
    
    // True if the connection is closed
    reader.closed();
    
    // Gets the next line, never blocks
    // Returns null if there is no data
    // This doesn't necessarily mean the connection is closed, it might be waiting!
    String line = reader.readLine(); // Gets the next line
    

    There are four possible states:

    1. Connection is open, no data is available
    2. Connection is open, data is available
    3. Connection is closed, data is available
    4. Connection is closed, no data is available

    You can distinguish between them with the isClosed() and ready() methods.

提交回复
热议问题