7

I have created an standalone application in which i want that when the user clicks on the run button then the terminal should open and a particular command should be executed on the terminal. I am able to open the terminal successfully using the following code...

Process process = null;  
try {  
    process = new ProcessBuilder("xterm").start();  
} catch (IOException ex) {  
    System.err.println(ex);  
}  

The above code opens a terminal window but I am not able to execute any command on it. Can anyone tell me how to do that?

Eric Leschinski
  • 146,994
  • 96
  • 417
  • 335
Harshit Agarwal
  • 1,345
  • 3
  • 20
  • 27

3 Answers3

5

Try

new ProcessBuilder("xterm", "-e", 
                   "/full/path/to/your/program").start()
Kilian Foth
  • 13,904
  • 5
  • 39
  • 57
4

Execute any command in linux as is,as what you type in the terminal:

    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStreamReader;

    public class CommandExecutor {
    public static String execute(String command){
        StringBuilder sb = new StringBuilder();
        String[] commands = new String[]{"/bin/sh","-c", command};
        try {
            Process proc = new ProcessBuilder(commands).start();
            BufferedReader stdInput = new BufferedReader(new 
                    InputStreamReader(proc.getInputStream()));

            BufferedReader stdError = new BufferedReader(new 
                    InputStreamReader(proc.getErrorStream()));

            String s = null;
            while ((s = stdInput.readLine()) != null) {
                sb.append(s);
                sb.append("\n");
            }

            while ((s = stdError.readLine()) != null) {
                sb.append(s);
                sb.append("\n");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return sb.toString();
    }

}

Usage:

CommandExecutor.execute("ps ax | grep postgres");

or as complex as:

CommandExecutor.execute("echo 'hello world' | openssl rsautl -encrypt -inkey public.pem -pubin | openssl enc -base64");

String command = "ssh user@database-dev 'pg_dump -U postgres -w -h localhost db1 --schema-only'";
CommandExecutor.execute(command);
ivanceras
  • 1,415
  • 3
  • 17
  • 28
2

Suppose you are trying your gedit command then you need to provide the full qualified path to gedit (e.g /usr/bin/gedit). Similarly for all other command specify the full path.

Antrromet
  • 15,294
  • 10
  • 60
  • 75