【发布时间】:2018-12-17 01:00:05
【问题描述】:
我目前正在尝试使用 java 中的进程来运行 jar 文件。我能够运行并阅读该进程打印的内容。我想要实现的是向进程写入命令。我正在运行的 jar 文件要求用户输入,我试图允许用户输入该输入。这是我当前不起作用的代码:
public class Main {
public static void main(String[] args) {
String command = "java -jar game.jar";
Process process = executeCommand(command);
CompletableFuture.runAsync(() -> {
Scanner scanner = new Scanner(System.in);
while (true) {
String input = scanner.nextLine();
if (input == null) {
continue;
}
executeCommand(process, input);
}
});
readOutput(process);
}
public static Process executeCommand(String command) {
try {
Process process = Runtime.getRuntime().exec(command);
return process;
} catch (IOException ex) {
ex.printStackTrace();
return null;
}
}
public static List<String> readOutput(Process process) {
List<String> output = new ArrayList<>();
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line;
while((line = reader.readLine()) != null) {
System.out.print(line + "\n");
output.add(line);
}
process.waitFor();
return output;
} catch (IOException ex) {
ex.printStackTrace();
return output;
} catch (InterruptedException ex) {
ex.printStackTrace();
return output;
}
}
public static void executeCommand(Process process, String command) {
try {
OutputStream out = process.getOutputStream();
out.write(command.getBytes());
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
【问题讨论】:
-
你怎么知道进程没有收到任何东西?也许在命令末尾添加
\n可能会有所帮助。 -
已添加 \n 无效。没有明显变化