Call external cmd within java

Handy way for solving a problem is to call an external program.
To retreive the result as a string, just ass few java line
Don't forget that calling a external program will add dependency upon your project


package demo;
 
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
 
public class CallShell {
 
    private static String streamToString(final InputStream stream) throws IOException {
        final BufferedReader in = new BufferedReader(new InputStreamReader(stream));
        final StringBuilder result = new StringBuilder();
        String line = in.readLine();
        while (line != null) {
            result.append(line).append("\n");
            line = in.readLine();
        }
        return result.toString();
    }
 
    private static String exec(final String cmd) {
        String result = null;
        try {
 
            final Process execResult = Runtime.getRuntime().exec(new String[]{"/bin/bash", "-c", cmd}, null, new File("."));
 
            execResult.waitFor();
            result = streamToString(execResult.getInputStream());
 
        } catch (final Exception ex) {
            System.out.println("Exception:" + ex.getMessage());
        }
        return result;
    }
 
    public static void main(String[] args) {
        System.out.println(exec("echo 'call from java'"));
        System.out.println(exec("/bin/bash --version"));
        System.out.println(exec("ls  "));
        System.out.println(exec("for I in `seq 1 10` ; do echo $I ; done"));
    }
}