Java Runtime.getRunTime().exec(CMD) not supporting pipes

*爱你&永不变心* 提交于 2019-12-01 00:58:00
Paul Vargas

Fortunately, there is a way to run a command containing pipes. The command must be prefixed with cmd /C. e.g.:

public static void main(String[] args) throws Exception {
    String command = "cmd /C netstat -ano | find \"3306\"";
    Process process = Runtime.getRuntime().exec(command);
    process.waitFor();
    if (process.exitValue() == 0) {
        Scanner sc = new Scanner(process.getInputStream(), "IBM850");
        sc.useDelimiter("\\A");
        if (sc.hasNext()) {
            System.out.print(sc.next());
        }
        sc.close();
    } else {
        Scanner sc = new Scanner(process.getErrorStream(), "IBM850");
        sc.useDelimiter("\\A");
        if (sc.hasNext()) {
            System.err.print(sc.next());
        }
        sc.close();
    }
    process.destroy();
}

Notes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!