打开一个shell并在java中与它的I / O交互 [英] opening a shell and interacting with its I/O in java
问题描述
我正在尝试打开一个shell(xterm)并与之交互(编写命令并读取shell的输出)
I am trying to open a shell (xterm) and interact with it (write commands and read the shell's output)
这是一个赢得的代码示例' t work:
Here is a sample of code which won't work:
public static void main(String[] args) throws IOException {
Process pr = new ProcessBuilder("xterm").start();
PrintWriter pw = new PrintWriter(pr.getOutputStream());
pw.println("ls");
pw.flush();
InputStreamReader in = new InputStreamReader(pr.getInputStream());
System.out.println(in.read());
}
当我执行此程序时,会打开一个xterm窗口并显示ls命令未输入。
只有当我关闭窗口时,我才会打印出-1并且没有从壳中读取任何内容
When I execute this program an "xterm" window opens and the "ls" command is not entered. Only when I close the window I get a "-1" printed and nothing is read from the shell
重要 -
我知道我可以使用:
处理pr = new ProcessBuilder(ls)。start();
I know I can just use:
Process pr = new ProcessBuilder("ls").start();
要获得输出,但我需要为其他用途打开xterm
To get the output, but I need the "xterm" opened for other uses
非常感谢
推荐答案
您的问题是xterm进程的标准输入和输出与终端窗口中可见的实际shell不对应。您可以直接运行shell进程,而不是xterm:
Your problem is that the standard input and output of the xterm process don't correspond to the actual shell that is visible in the terminal window. Rather than an xterm you may have more success running a shell process directly:
Process pr = new ProcessBuilder("sh").start();
这篇关于打开一个shell并在java中与它的I / O交互的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!