繁体   English   中英

在 Java 中打开一个 shell 并与其 I/O 交互

[英]opening a shell and interacting with its I/O in java

我正在尝试打开一个 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”窗口打开并且没有输入“ls”命令。 只有当我关闭窗口时,我才会打印“-1”并且没有从外壳读取任何内容

重要的-

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

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

非常感谢

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

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

    }

}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM