Harshit Agarwal
Harshit Agarwal

Reputation: 1345

executing commands on terminal in linux through java

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?

Upvotes: 7

Views: 11171

Answers (3)

ivanceras
ivanceras

Reputation: 1455

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);

Upvotes: 4

Antrromet
Antrromet

Reputation: 15414

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.

Upvotes: 2

Kilian Foth
Kilian Foth

Reputation: 14336

Try

new ProcessBuilder("xterm", "-e", 
                   "/full/path/to/your/program").start()

Upvotes: 5

Related Questions