首页 文章

Groovy InputStream读取挂起

提问于
浏览
1

我正在尝试使Java程序更“Groovy” . java代码读取一个InputStream,如下所示:

static int myFunction(InputStream is) throws IOException {
    int b=is.read();
    if (b==0) return b;
    StringBuffer sb=new StringBuffer();
    int c;
    boolean done = false;
    while(!done) {
        c=is.read();
        sb.append((char)c);
        if(c == '\n') {
           done=true;
        }
    }
    System.out.println(sb.toString());
    if (b == 1) throw new IOException("blah");
    return b;
}

我的Groovy版本看起来像这样:

def myFunction(InputStream is) throws IOException {
    int b=is.read()
    if (b==0) return b
    def reader = new BufferedReader(new InputStreamReader(is))
    reader.eachLine { println(it) } 
    println("DONE")
    if (b == 1) throw new IOException("blah")
    return b
}

它打印流的内容,然后挂起就像它试图阅读更多 . 它从不打印“DONE”(为调试添加) . 接下来我尝试使用is.eachByte并传递一个带有显式“if(c =='\ n')返回”的闭包,但我发现闭包内部的返回更像是一个继续并且实际上并没有突破关闭 . 知道我做错了什么吗?

1 回答

  • 1

    代替

    reader.eachLine { println(it) }
    

    你能试一下吗

    println reader.readLine()
    

相关问题