从管道到另一个进程的 InputStream 保持阻塞

InputStream from a pipe to another process remains blocked

我正在尝试在 Java 中做一些基本的管道。我写了一个非常简单的测试程序,但是代码在 while 循环中一直被阻塞,因为 cat 的 stdout 似乎没有输入。我哪里做错了?

public static void main(String[] arguments) throws Exception{
    Process p=Runtime.getRuntime().exec("cat");
    PrintStream out=new PrintStream(p.getOutputStream());
    Scanner in=new Scanner(p.getInputStream());
    out.println("hello");
    while(in.hasNextLine()){
        System.out.println(in.nextLine());
    }
}

默认情况下 PrintStream 不会自动刷新。您可以使用 new PrintStream(p.getOutputStream(), true); 构建它以启用自动刷新,或者在 out.println("hello"); 之后添加对 out.flush() 的调用以在写入后手动刷新字符串。两者都会导致 in 读取您打印到 out 的内容。

in.hasNextLine() 需要行尾,这可能是问题所在。尝试以下是否有效

    InputStream in = p.getInputStream();
    for (int c;(c=in.read())!= -1;) {
        System.out.print((char)c);
    }