java shell 实时交互,打开一个shell并在java中与它的I / O交互

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());

}

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

IMPORTANT-

I know I can just use:

Process pr = new ProcessBuilder("ls").start();

To get the output, but I need the "xterm" opened for other uses

Thanks a lot

解决方案

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();

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值