Groovy InputStream读取挂起

时间:2012-03-28 21:58:10

标签: groovy

我正在尝试使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 个答案:

答案 0 :(得分:1)

而不是

reader.eachLine { println(it) } 

你能试试吗

println reader.readLine()