Can I peek on a BufferedReader?

2019-02-08 01:58发布

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

8条回答
霸刀☆藐视天下
2楼-- · 2019-02-08 02:24

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".

查看更多
别忘想泡老子
3楼-- · 2019-02-08 02:26

my solution was.. extending BufferedReader and use queue as buf, then you can use peek method in queue.

public class PeekBufferedReader extends BufferedReader{

    private Queue<String>       buf;
    private int                 bufSize;

    public PeekBufferedReader(Reader reader, int bufSize) throws IOException {
        super(reader);
        this.bufSize = bufSize;
        buf = Queues.newArrayBlockingQueue(bufSize);
    }

    /**
     * readAheadLimit is set to 1048576. Line which has length over readAheadLimit 
     * will cause IOException.
     * @throws IOException 
     **/
    //public String peekLine() throws IOException {
    //  super.mark(1048576);
    //  String peekedLine = super.readLine();
    //  super.reset();
    //  return peekedLine;
    //}

    /**
     * This method can be implemented by mark and reset methods. But performance of 
     * this implementation is better ( about 2times) than using mark and reset  
     **/
    public String peekLine() throws IOException {
        if (buf.isEmpty()) {
            while (buf.size() < bufSize) {
                String readLine = super.readLine();
                if (readLine == null) {
                    break;
                } else {
                    buf.add(readLine);
                }
            }
        } else {
            return buf.peek();
        }
        if (buf.isEmpty()) {
            return null;
        } else {
            return buf.peek();
        }
    }

    public String readLine() throws IOException {
        if (buf.isEmpty()) {
            while (buf.size() < bufSize) {
                String readLine = super.readLine();
                if (readLine == null) {
                    break;
                } else {
                    buf.add(readLine);
                }
            }
        } else {
            return buf.poll();
        }
        if (buf.isEmpty()) {
            return null;
        } else {
            return buf.poll();
        }
    }
    public boolean isEmpty() throws IOException {
        if (buf.isEmpty()) {
            while (buf.size() < bufSize) {
                String readLine = super.readLine();
                if (readLine == null) {
                    break;
                } else {
                    buf.add(readLine);
                }
            }
        } else {
            return false;
        }
        if (buf.isEmpty()) {
            return true;
        } else {
            return false;
        }
    }
}
查看更多
登录 后发表回答