如何在 Java 中回答来自终端的命令

How to answer a command from the Terminal in Java

我想从 Java 执行一个命令,但是这个命令要我给它一个用户名。

像这个例子:

$ my command

[command] Username:_

那么如何在 Java 中为命令提供我的用户名?

目前我的代码是这样的:

    Process p = Runtime.getRuntime().exec(command);
    BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
    String s;
    while ((s = br.readLine()) != null){
        System.out.println(s);
    }
    br.close();
    p.waitFor();
    p.destroy();

您需要创建另一个线程并通过 process#getOutputStream() 获取用户输入。请参阅以下示例:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;

public class ProcessWithInput {

    public static void main(String[] args) throws IOException, InterruptedException {
        Process p = Runtime.getRuntime().exec("cat");
        OutputStream os = p.getOutputStream();
        os.write("Hello World".getBytes());
        os.close();
        BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
        String s;
        while ((s = br.readLine()) != null) {
            System.out.println(s);
        }
        br.close();
        p.waitFor();
        p.destroy();
    }
}

当然,你需要做适当的error/exception处理等

其他选项是使用 ProcessBuilder,它允许您通过文件提供输入。