我目前正在尝试使用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();
}
}
}
答案 0 :(得分:0)
我能够通过添加out.flush()来解决问题
public static void executeCommand(Process process, String command) {
try {
OutputStream out = process.getOutputStream();
out.write(command.getBytes());
out.flush();
} catch (IOException ex) {
ex.printStackTrace();
}
}