Executing process in Linux

In automation testing, there are often situations where we need to execute the process and see the output after execution is finished. Below example shows how to execute the linux commands using Java. Note that we have executed piped command "ls | wc" using Runtime class.


    public void testProcess(){
        String output;
        Process p;
        try {
            String[] cmd = { "/bin/sh", "-c", "ls | wc" };
            p = Runtime.getRuntime().exec(cmd);
            BufferedReader br = new BufferedReader(
                    new InputStreamReader(p.getInputStream()));
            while ((output = br.readLine()) != null)
                System.out.println( output);
            System.out.println ("exit code " + p.exitValue());
        } catch (Exception e) {}

Youtube | Facebook | Twitter | Website Home | Online Grocery Shopping Brisbane