在Java中,如果有立即可用的数据,则期望从Process的inputStream读取。
但是当进程不会立即产生数据时,似乎不可能检索数据?

单元测试 :

@Test
public void testForkingProcess() throws Exception {
            String [] cmds = new String[]{"echo this is a test", "sleep 2 ; echo this is a test"};
    for(String cmd: cmds) {
        Process p = Runtime.getRuntime().exec(cmd);
        byte[] buf = new byte[100];
        int len = 0;
        long t0 = System.currentTimeMillis();
        while(len < 15 && (System.currentTimeMillis() - t0) < 5000) {
            int newLen = p.getInputStream().read(buf, len, buf.length - len);
            if(newLen != -1) {
                len += newLen;
            }
        }
        long t1 = System.currentTimeMillis();
        System.out.println("elapse time : " + (t1 - t0) +" ms");
        System.out.println("read len : " + len);
        p.destroy();
    }
}


控制台输出:

    elapse time : 1 ms
    read len : 15
    elapse time : 5000 ms
    read len : 0


是否有人对此行为以及如何处理流以检索数据的线索。

另一个简单的例子:

@Test
public void testMoreSimpleForkingProcess() throws Exception {
    String [] cmds = new String[]{"echo this is a test", "sleep 2 ; echo this is a test"};
    for(String cmd: cmds) {
        Process p = Runtime.getRuntime().exec(cmd);
        byte[] buf = new byte[100];
        int len = 0;
        int newLen = 0;
        while(newLen >= 0) {
            newLen = p.getInputStream().read(buf, len, buf.length - len);
            if(newLen != -1) {
                len += newLen;
            }
        }
        p.getInputStream().close();
        System.out.println("read len : " + len);
        p.destroy();
    }

}


控制台输出:

    read len : 15
    read len : 0

最佳答案

如何从Process inputStream读取不立即可用?


块。您不需要计时的东西。您不知道该过程将以多快的速度产生输出。只是阻塞读取,然后重复直到流结束。

您还需要消耗错误流,还需要关闭流程的输入流。您已经在接收流结束时正在睡觉。无意义。

关于java - 如何从Process inputStream读取不是立即可用,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/46807127/

10-14 12:22
查看更多