Wednesday, June 4, 2008

Execute shell commands from java

(Probably only works on unix)

To just execute without worrying about returned output:

Runtime.getRuntime().exec(new String[] { "sh", "-c", "mv a b" });

(This example would run "mv a b" in the shell)

To execute and retreive the returned output:

Runtime rt = Runtime.getRuntime();
Process p = rt.exec((new String[] { "sh", "-c", "ls *.tmp" }));
try{
p.waitFor();
InputStream is = p.getInputStream();
java.io.DataInputStream din = new java.io.DataInputStream(is);
} catch(Exception e){}

(din will have the returned output of running "ls *.tmp" in the shell)

No comments: