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?
As others said, you may run your external program without xterm. However, if you want to run it in a terminal window, e.g. to let the user interact with it, xterm allows you to specify the program to run as parameter.
In Java code this becomes:
Or, using ProcessBuilder:
I vote for Karthik T's answer. you don't need to open a terminal to run commands.
For example,
The output:
I know this question is quite old, but here's a library that encapsulates the ProcessBuilder api.
You need to run it using
bash
executable like this:Update: As suggested by xav, it is advisable to use ProcessBuilder instead:
You don't actually need to run a command from an xterm session, you can run it directly:
If the process responds interactively to the input stream, and you want to inject values, then do what you did before:
Don't forget the '\n' at the end though as most apps will use it to identify the end of a single command's input.
I don't know why, but for some reason, the "/bin/bash" version didn't work for me. Instead, the simpler version worked, following the example given here at Oracle Docs.