【问题标题】:Execute commands to running process对正在运行的进程执行命令
【发布时间】: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 无效。没有明显变化

标签: java process


【解决方案1】:

我可以通过添加 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();
    }

}

【讨论】:

  • 以阻塞方式写入输出流是危险的,它取决于平台是否有缓冲区。您通常在单独的线程中执行此操作。但是在写入之前启动读取器线程可能就足够了,以防它阻塞,因为目标命令想要在读取之前写入一些东西。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-11-09
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多