如何从Java运行UNIX终端并向其发送命令? [英] How do i run a UNIX terminal from Java and send commands to it?
问题描述
关于主题,下面的代码
Process proc = null;
try {
String[] cmdss= {"gnome-terminal"};
proc = Runtime.getRuntime().exec(cmdss, null, wd);
} catch (IOException e) {
e.printStackTrace();
}
从Ubuntu运行终端.
Runs the terminal form Ubuntu.
运行终端后如何向终端发出命令?
How do I issue commands into the terminal after running the termnal?
例如:运行终端并运行诸如"ls"之类的命令.
eg: running the terminal and run command such as "ls" etc.
推荐答案
您可以在命令行上为 gnome-terminal
提供一些选项,它应该执行什么.
You can give gnome-terminal
some options on the command line what it shall execute.
gnome-terminal -e /my/fortran/program
-x
选项可为您提供大致相同的好处,但您可以将命令行拆分为单独的单词.
The -x
option gives you roughly the same benefit but you can split the commandline into separate words.
-e
和 -x
都使用可选参数运行该程序,同时将程序的标准输入和输出连接到终端.这样用户可以与终端进行正确的交互.
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.
示例:
gnome-terminal -x bash -c "ls; echo '<enter>'; read"
这将打开终端并运行程序" bash
. bash
将获得两个参数: -c
和 ls;回声..;阅读
. -c
选项使bash解析并执行下一个参数.这将调用 ls
,然后调用 echo ...
,然后调用 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.
在Java中,您必须将参数适当地分成这样的数组:
In Java you must split the arguments appropriately into an array like this:
String cmd[] = {"gnome-terminal", "-x", "bash", "-c", "ls; echo '<enter>'; read" };
这篇关于如何从Java运行UNIX终端并向其发送命令?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!