我正在制作一个简单的GUI界面为一个TUI我的世界服务器,我需要发出命令到该程序的基础上的GUI事件(按钮点击等)。我创建了一个进程构建器,但是如何给正在运行的程序更多的命令呢?
我正在尝试完成的一个示例是用Java打开一个命令行程序,该程序询问我的姓名。我的问题是,我该如何给这个程序起我的名字。
我已经看过许多关于类似事情的已有的Stack-exchange*帖子,但它们都不适合我。
我在linux btw上,如果这很重要的话。
public Process runCommand(String command) throws IOException {
ProcessBuilder pb = new ProcessBuilder("/bin/bash", "-c", command, "-S");
Process process = pb.start(); // Executes the command
return process;
}
public void showCommandOutput(Process process) {
BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line = ""; // Empty String to put the output in
try {
while ((line = reader.readLine()) != null) { // For every line in the shell output
System.out.println(line); // Print the line
}
try {
process.waitFor();
} catch (InterruptedException e) {
e.printStackTrace(); // If this goes wrong, display stack trace
} finally {
quitServer(0); // External function for closing program, self explanatory
}
} catch (IOException e) {
e.printStackTrace();
}
}提前谢谢你。
发布于 2020-03-21 04:22:03
你已经走到一半了。调用pb.start()时返回的Process对象包含与外部程序通信所需的输入流和输出流。您已经在从process.getInputStream()中读取数据,以获取进程的输出。要向其发送输入,只需将数据写入process.getOutputStream()流。
在将readLine()与bash这样的进程一起使用时,您应该小心。当bash写出命令提示符时,它不会以换行符结尾(因此您可以在同一行中输入命令)。所以你的readLine()将永远等待不会到来的换行符。您可能希望使用无缓冲读取,并检查数据中是否有任何类似提示的内容。
如果您确定您的程序将输出文本,期望得到响应,然后读取您的输入,则可以在现有循环中执行此操作。在读取检测到的每一行之后提供一个命令是一个提示符。例如:
PrintStream commandWriter = new PrintStream(process.getOutputStream());
while ((line = reader.read()) != null) { // For every line in the shell output
// if I know prompts end with a certain substring
if (line.endsWith("$> ")) {
commandWriter.println("echo \"this is a command I sent to a process\"");
}
else {
System.out.println("Received from process: " + line);
}
}但是,如果您正在与之交互的程序更具交互性,那么您可能需要启动单独的线程来读取和写入输入/输出。您必须小心处理这些进程,以确保在数据可用时不断读取这些进程中的数据。如果您忘记这样做,外部程序可能会挂起,当它卡在一个满的缓冲区。
https://stackoverflow.com/questions/60771031
复制相似问题