开发者

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

开发者 https://www.devze.com 2023-04-08 21:04 出处:网络
Regarding the topic, the code below Process proc = null; try { String[] cmdss= {\"gnome-terminal\"}; proc = Runtime.getRuntime().exec(cmdss, null, wd);

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 r开发者_如何学Cun command such as "ls" etc.


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" };
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号