Java 我可以查看 BufferedReader 吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2517638/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 08:43:38  来源:igfitidea点击:

Can I peek on a BufferedReader?

javabufferedreaderpeek

提问by There is nothing we can do

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

有没有办法检查BufferedReader对象是否可以读取?像 C++ 之类的东西cin.peek()。谢谢。

采纳答案by pgmura

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

您可以尝试“boolean ready()”方法。来自 Java 6 API 文档:“如果缓冲区不为空,或者基础字符流已准备好,则缓冲字符流已准备好。”

BufferedReader r = new BufferedReader(reader);
if(r.ready())
{
   r.read();
}

回答by Kyle Rozendo

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

以下代码将查看 Stream 中的第一个字节。应该充当你的窥视。

BufferedReader bReader = new BufferedReader(inputStream);
bReader.mark(1);
int byte1 = bReader.read();
bReader.reset();

回答by Taylor Leese

BufferedReader br = new BufferedReader(reader);
br.mark(1);
int firstByte = br.read();
br.reset();

回答by Gavin H

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

您可以使用PushbackReader。使用它,您可以读取一个字符,然后取消读取它。这基本上允许您将其推回。

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

回答by BalusC

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.

正常的习惯用法是在循环中检查 if BufferedReader#readLine()not return null。如果到达流结尾(例如文件结尾、套接字关闭等),则返回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 BufferedReaderis been chosen), then use BufferedReader#ready()instead:

如果您不想逐行阅读(这是BufferedReader选择a 的主要原因),请BufferedReader#ready()改用:

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

回答by skaffman

You could use a PushBackReaderto 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".

您可以使用 aPushBackReader读取字符,然后“将其推回”。这样你就可以确定有东西在那里,而不会影响它的整体状态——“偷看”。

回答by leonbloy

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=4090471I'd rather go with the PushbackReader option.

pgmura 的答案(依赖于ready() 方法)很简单而且有效。但请记住,这是因为 Sun 对方法的实现;这与文档并不完全一致。如果这种行为很关键,我不会依赖它。请参阅此处http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4090471我宁愿使用 PushbackReader 选项。

回答by yelang moon

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

我的解决方案是..扩展BufferedReader并将队列用作buf,然后您可以在队列中使用peek方法。

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;
        }
    }
}