java - 执行后向Runtime.getRuntime().exec()发送参数

标签 java process runtime

我需要在我的 java 程序中执行一个命令,但在执行该命令后,它需要另一个参数(在我的例子中是一个密码)。如何管理 Runtime.getRuntime().exec() 的输出过程以接受进一步执行的参数?

我尝试了 new BufferedWriter(new OutputStreamWriter(signingProcess.getOutputStream())).write("123456"); 但它没有用。

最佳答案

您的程序没有 --password 选项吗?通常所有基于命令行的程序都会这样做,主要是针对脚本。

Runtime.getRuntime().exec(new String[]{"your-program", "--password="+pwd, "some-more-options"});

或者更复杂且更容易出错的方法:

try {
    final Process process = Runtime.getRuntime().exec(
            new String[] { "your-program", "some-more-parameters" });
    if (process != null) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    DataInputStream in = new DataInputStream(
                            process.getInputStream());
                    BufferedReader br = new BufferedReader(
                            new InputStreamReader(in));
                    String line;
                    while ((line = br.readLine()) != null) {
                        // handle input here ... ->
                        // if(line.equals("Enter Password:")) { ... }
                    }
                    in.close();
                } catch (Exception e) {
                    // handle exception here ...
                }
            }
        }).start();
    }
    process.waitFor();
    if (process.exitValue() == 0) {
        // process exited ...
    } else {
        // process failed ...
    }
} catch (Exception ex) {
    // handle exception
}

此示例打开一个新线程(请记住并发和同步),该线程将读取您的进程的输出。类似地,只要它没有终止,您就可以为您的进程提供输入:

if (process != null) {
    new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                DataOutputStream out = new DataOutputStream(
                        process.getOutputStream());
                BufferedWriter bw = new BufferedWriter(
                        new OutputStreamWriter(out));
                bw.write("feed your process with data ...");
                bw.write("feed your process with data ...");
                out.close();
            } catch (Exception e) {
                // handle exception here ...
            }
        }
    }).start();
}

希望这对您有所帮助。

关于java - 执行后向Runtime.getRuntime().exec()发送参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16688902/

相关文章:

clojure - 在运行时设置 Clojure "constants"

java - 在Play Framework中生成html View 模板的片段

java - 如何创建内存中的 JarFile?

java - Spring Boot中的多个index.html

java - RxJava 将一个列表转换为另一个列表时遇到问题

c - C中子进程之间的管道

deployment - Web 应用程序开发过程 - 版本控制、错误跟踪、单元测试、部署

c - 一个调用 exit() 但没有变成僵尸的子进程

c++ - 在运行时动态组合 Boost.Spirit.Qi 规则(任意数量的备选方案)

performance - 字符串连接检查算法的运行时