gpt4 book ai didi

java - 如何在 Java 中响应来自终端的命令

转载 作者:行者123 更新时间:2023-11-30 10:11:33 24 4
gpt4 key购买 nike

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

当然,您需要进行适当的错误/异常处理等。

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

关于java - 如何在 Java 中响应来自终端的命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52389213/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com