Melvin Chan Kok Leng
Melvin Chan Kok Leng

Reputation: 23

How do i run a UNIX terminal from Java and send commands to it?

Regarding the topic, the code below


    Process proc = null;
    try {
        String[] cmdss= {"gnome-terminal"};


        proc = Runtime.getRuntime().exec(cmdss, null, wd);
    } catch (IOException e) {
        e.printStackTrace();
    }

Runs the terminal form Ubuntu.

How do I issue commands into the terminal after running the termnal?

eg: running the terminal and run command such as "ls" etc.

Upvotes: 2

Views: 3643

Answers (1)

A.H.
A.H.

Reputation: 66213

You can give gnome-terminal some options on the command line what it shall execute.

gnome-terminal -e /my/fortran/program

The -x option gives you roughly the same benefit but you can split the commandline into separate words.

Both -e and -x run the program with optional arguments while connecting the program`s standard input and output to the terminal. So the user can interact with the terminal properly.

Example:

gnome-terminal -x bash -c "ls; echo '<enter>'; read"

This will open the terminal and run the "program" bash. bash will get two arguments: -c and ls; echo ....; read. The -c option makes bash parsing and executing the next argument. This will call ls, then echo ... then read which waits for the return key.

In Java you must split the arguments appropriately into an array like this:

String cmd[] = {"gnome-terminal", "-x", "bash", "-c", "ls; echo '<enter>'; read" };

Upvotes: 2

Related Questions