1.
is there a better way to do this other than Runtime.getRuntime()
What do you mean with "better"?
2.
Runtime.getRuntime().exec(myCommand);
This works very well, but keep in mind that the .bashrc (or similar environment setup) will not be executed in this case. Moreover, you don't capture the output.
3.
Just as a auxiliary note. Here is my interface to the shell:
import java.io.*;
public class Shell
{
Process proc;
BufferedReader in;
BufferedReader err;
PrintWriter out;
public Shell() throws IOException
{
proc = Runtime.getRuntime().exec("/bin/bash");
in = new BufferedReader(new InputStreamReader(proc.getInputStream()));
err = new BufferedReader(new InputStreamReader(proc.getErrorStream()));
out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(proc.getOutputStream())), true);
exec("source ~/.bashrc");
}
public void exec(String cmd)
{
out.println(cmd);
try {
while (in.ready())
System.out.println(in.readLine());
while (err.ready())
System.err.println(err.readLine());
}
catch (IOException ioe) {
ioe.printStackTrace();
}
}
public void close()
{
try {
out.println("exit");
proc.waitFor();
while (in.ready())
System.out.println(in.readLine());
while (err.ready())
System.err.println(err.readLine());
in.close();
out.close();
proc.destroy();
}
catch (IOException e) {
e.printStackTrace();
}
catch (InterruptedException e) {
e.printStackTrace();
}
}
public static void execute(String command) throws IOException
{
System.out.println("Executing: " + command);
Shell shell = new Shell();
shell.exec(command);
shell.close();
}
public static void main(String[] args) throws IOException
{
Shell.execute("ls -l ~");
}
}