Java执行外部Linux命令,并获取输出,以及解决管道、重定向命令无法执行的坑

2020-12-28 58点热度 0人点赞 0条评论

Java执行外部命令,获取输出,可能是错误流,也可能是标准输出流,可以根据需要区分开来输出,我目前是混在一起输出了,

private static String executeCommand() {
        StringBuilder sb = new StringBuilder();

        try {
            Process proc = Runtime.getRuntime().exec("java -version");
            BufferedReader stdInput = new BufferedReader(new InputStreamReader(proc.getInputStream()));
            BufferedReader stdError = new BufferedReader(new InputStreamReader(proc.getErrorStream()));

            // Read the output from the command
            String s = null;
            while ((s = stdInput.readLine()) != null) {
                sb.append(s).append("\n");
            }

            // Read any errors from the attempted command
            while ((s = stdError.readLine()) != null) {
                sb.append(s).append("\n");
            }
        } catch (Exception e) {
            sb.append(e.getMessage());
        }
        return sb.toString().trim();
}

另外发现执行管道命令或者重定向命令的时候,提示无法执行,例如执行 ps aux|grep java echo 'hello'>/opt/test.txt

可以修改如下解决

Process proc = Runtime.getRuntime().exec(new String[]{"/bin/sh", "-c", "ps aux|grep java"});

 

 

Terry

文章评论

*

code