如何使用Java获取Linux命令“ pv”的StandardOutput

时间:2019-03-25 03:41:20

标签: java linux

我想通过运行SQL脚本还原数据库并监视还原进度。此外,我使用pv命令查看还原的进度,它在Linux终端下运行良好,并且可以看到进度。但是当我使用Java执行它时,无法获得指示进度的pv的标准输出。

public void restore() throws IOException, InterruptedException {

    String s  = "pv -p /var/test.sql | mysql -h127.0.0.1 -uroot -ptest -D test";
    Process process = null;
    String[] cmd = { "/bin/sh", "-c", s};

    try {
        process = Runtime.getRuntime().exec(cmd);
        BufferedReader stdInput = new BufferedReader(new
                InputStreamReader(process.getInputStream()));

        BufferedReader stdError = new BufferedReader(new
                InputStreamReader(process.getErrorStream()));

        System.out.println("Here is the standard output of the command:\n");
        String s1 = null;
        while ((s1 = stdInput.readLine()) != null) {
            System.out.println(s1);
        }

        System.out.println("Here is the standard error of the command (if any):\n");
        while ((s1 = stdError.readLine()) != null) {
            System.out.println(s1);
        }
        System.out.println("after");
    } catch (Exception e) {
        e.printStackTrace();
    }
}

0 个答案:

没有答案