在 Java 中打开一个 shell 并与其 I/O 交互 [英] opening a shell and interacting with its I/O in java

查看:31
本文介绍了在 Java 中打开一个 shell 并与其 I/O 交互的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试打开一个 shell (xterm) 并与之交互(编写命令并读取 shell 的输出)

I am trying to open a shell (xterm) and interact with it (write commands and read the shell's output)

这是一个不起作用的代码示例:

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"并且没有从 shell 中读取任何内容

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

重要 -

我知道我可以使用:
Process 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();

这篇关于在 Java 中打开一个 shell 并与其 I/O 交互的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆