Execute a command in Linux using Java and fetch the output

前端 未结 3 1453
野趣味
野趣味 2020-12-30 17:26

I am using Groovy to execute commands on my Linux box and get back the output, but I am not able to use | pipes somehow (I think) or maybe it is not waiting for

3条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-30 18:08

    The pipe | is a feature of a shell like bash. To use a pipe you need to run a shell, like

    "/bin/bash", "-c", "uname -a | awk '{print $2}'"
    

    To use ProcessBuilder with redirection you can do

    public static void main(String... args) throws IOException, InterruptedException {
        final String cmd = "uname -a | awk '{print $1 \" \" $3}'";
        System.out.println(cmd + " => " + run(cmd));
    }
    
    private static String run(String cmd) throws IOException, InterruptedException {
        final ProcessBuilder pb = new ProcessBuilder("/bin/bash", "-c", cmd);
        pb.redirectErrorStream();
        final Process process = pb.start();
        final InputStream in = process.getInputStream();
        final byte[] bytes = new byte[1024];
        final ByteArrayOutputStream baos = new ByteArrayOutputStream();
    
        // you must read the output as the program runs or it can stall.
        for (int len; (len = in.read(bytes)) > 0;)
            baos.write(bytes, 0, len);
        process.waitFor();
        return baos.toString(); // assuming the default char encoding is ok.
    }
    

    prints

    uname -a | awk '{print $1 " " $3}' => Linux 2.6.18-274.3.1.el5
    

提交回复
热议问题