5

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

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

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 中读取任何内容

重要的-

我知道我可以使用:
Process pr = new ProcessBuilder("ls").start();

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

非常感谢

4

2 回答 2

5

您的问题是 xterm 进程的标准输入和输出与终端窗口中可见的实际 shell 不对应。与 xterm 相比,您可能会更成功地直接运行 shell 进程:

Process pr = new ProcessBuilder("sh").start();
于 2012-11-17T14:36:39.297 回答
2

是一个完整的 java 主要示例,说明如何与shellon进行交互java 8(在 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();
        }

    }

}
于 2016-02-08T02:07:11.653 回答