Techminded

Execute system command from Java

We will take canonical hello world up for demonstration.

import java.util.Scanner;
import java.io.*;
 
public class Program {
    public static void main(String[] args) {    	
    	try {
    		Process p = Runtime.getRuntime().exec("echo 'hello' > /tmp/hello.txt");
    		Scanner sc = new Scanner(p.getInputStream());    		
    		while (sc.hasNext()) System.out.println(sc.nextLine());
    	}
    	catch (IOException e) {
    		System.out.println(e.getMessage());
    	}
    }
}

It will not work even if you pass all argments as string array. The solution I found is to call shell directly with -c parameter to execute command like this:

String command = "echo 'hello' > /tmp/hello.txt";
Process p = new ProcessBuilder("/bin/sh", "-c", command).start();  

This makes command able to be executed even with spaces and things like piping.

Links

http://rosettacode.org/wiki/Execute_a_system_command

Comments