打开一个shell并在java中与其I / O进行交互

我想打开一个shell(xterm)并与之交互(写入命令并读取shell的输出)

这是一个不能工作的代码示例:

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”窗口并且不input“ls”命令。 只有当我closures窗口,我得到一个“-1”打印,没有任何东西从shell读取

重要-

我知道我可以使用:
Process pr = new ProcessBuilder(“ls”)。start();

要获得输出,但我需要打开其他用途的“xterm”

非常感谢

Solutions Collecting From Web of "打开一个shell并在java中与其I / O进行交互"

您的问题是,xterm进程的标准输入和输出不符合在终端窗口中可见的实际shell。 而不是一个xterm,你可能会更直接地运行一个shell进程:

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

在这里,一个完整的java如何与java 8上的shell交互的主要例子(真的很简单,在java 4,5,6做什么)

输出示例

 $ javac Main.java $ java Main echo "hi" hi 

代码

 import java.io.*; import java.util.Arrays; import java.util.List; import java.util.Scanner; public class Main { public static void main(String[] args) throws IOException, InterruptedException { final List<String> commands = Arrays.asList("/bin/sh"); final Process p = new ProcessBuilder(commands).start(); // imprime erros new Thread(() -> { BufferedReader ir = new BufferedReader(new InputStreamReader(p.getErrorStream())); String line = null; try { while((line = ir.readLine()) != null){ System.out.printf(line); } } catch(IOException e) {} }).start(); // imprime saida new Thread(() -> { BufferedReader ir = new BufferedReader(new InputStreamReader(p.getInputStream())); String line = null; try { while((line = ir.readLine()) != null){ System.out.printf("%s\n", line); } } catch(IOException e) {} }).start(); // imprime saida new Thread(() -> { int exitCode = 0; try { exitCode = p.waitFor(); } catch(InterruptedException e) { e.printStackTrace(); } System.out.printf("Exited with code %d\n", exitCode); }).start(); final Scanner sc = new Scanner(System.in); final BufferedWriter bf = new BufferedWriter(new OutputStreamWriter(p.getOutputStream())); final String newLine = System.getProperty("line.separator"); while(true){ String c = sc.nextLine(); bf.write(c); bf.newLine(); bf.flush(); } } }