简体   繁体   English

如何抑制BufferReader的空输出?

[英]How can I suppress the null output of a BufferReader?

Using the following code to split the output of a reader into strings which are then used in a constructor. 使用以下代码将读取器的输出拆分为字符串,然后在构造函数中使用。 However when the bufferreader reaches the end of the stream it outputs null, which then causes a null pointer exception in the constructor. 但是,当bufferreader到达流的末尾时,它输出null,然后在构造函数中导致空指针异常。

List<Pattern> resultList = new LinkedList<Pattern>();
    BufferedReader buff = new BufferedReader(r);
    String current;
    while (buff != null) {
        current = buff.readLine();
        System.out.println(current);
        Pattern p = new Pattern(current);
        resultList.add(p);

        }
    return resultList;

I've tried putting an if statement to test if the current string is null, however I don't know what to put in the body of the if-clause. 我已经尝试使用if语句来测试当前字符串是否为null,但是我不知道在if子句的主体中放入什么。 Any help would be greatly appreciated 任何帮助将不胜感激

buff is never going to be null - it's the return value of readLine which is null when you reach the end of the data. buff永远不会为null - 它是readLine的返回值,当您到达数据末尾时,它返回null。 That's what you need to check, typically with code which assigns the value to a variable and checks it in one go: 就是您需要检查的内容,通常使用代码将值分配给变量并一次性检查:

String current;
while ((current = buff.readLine()) != null) {
    System.out.println(current);
    Pattern p = new Pattern(current);
    resultList.add(p);
}

Instead of putting an if into the while , change the conditions of your loop from: 而不是将if放入while ,而是更改循环的条件:

while (buff != null)

to: 至:

while ((current = buff.readLine()) != null)  

buff will not become null as a result of reaching the end of the stream, but current will become null when there is no more input to be returned 到达流的末尾时buff不会变为null ,但是当没有更多的输入要返回时, current将变为null

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM