how to run a command at terminal from java program?

java, linux, terminal

Solution

You need to run it using `bash` executable like this:

Runtime.getRuntime().exec("/bin/bash -c your_command");

Update: As suggested by xav, it is advisable to use ProcessBuilder instead:

String[] args = new String[] {"/bin/bash", "-c", "your_command", "with", "args"};
Process proc = new ProcessBuilder(args).start();

Problem

I need to run a command at terminal in Fedora 16 from a JAVA program. I tried using ``` Runtime.getRuntime().exec("xterm"); ``` but this just opens the terminal, i am unable to execute any command. I also tried this: ``` OutputStream out = null; Process proc = new ProcessBuilder("xterm").start(); out = proc.getOutputStream(); out.write("any command".getBytes()); out.flush(); ``` but still i can only open the terminal, but can't run the command. Any ideas as to how to do it?

Original source

Related problems