运行时Java Process打印输出

时间:2017-03-01 11:20:37

标签: java linux bash

我正在尝试在Java程序中运行split命令。当我在控制台中使用参数--verbose运行它时,它会按如下方式打印生成的块:

creating file 'chunk00'
creating file 'chunk01'
creating file 'chunk02'

但是当我在java程序中运行它时,这些输出将在完成该过程后打印。在split进程运行时我必须做什么才能获得输出?

我使用了以下代码:

ProcessBuilder pb = new ProcessBuilder("split", "-a 2", "-d", "-b 52MB","--verbose",path+"/"+db,"chunk");
        pb.redirectErrorStream(true);
        File workingFolder = new File("/home/hajibaba");
        pb.directory(workingFolder);
        Process proc = pb.start();
        BufferedReader stdInput = new BufferedReader(new InputStreamReader(proc.getInputStream()));

        // read the output from the command
        String s = null;
        while ((s = stdInput.readLine()) != null)
        {
            System.out.println(s);
        }
        proc.waitFor();

但是,它适用于使用echo打印相同结果的bash脚本。

1 个答案:

答案 0 :(得分:1)

I / O在交互式会话中进行行缓冲,但在写入管道时进行缓冲。

要解决此问题,您可以使用unbuffer命令关闭缓冲。

ProcessBuilder pb = new ProcessBuilder("unbuffer", "split", "-a2", "-d", "-b52MB","--verbose",path+"/"+db,"chunk");

https://unix.stackexchange.com/questions/25372/turn-off-buffering-in-pipe