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

5

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

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


我尝试使用新的BufferedWriter(new OutputStreamWriter(signingProcess.getOutputStream())).write("123456"),但是没有起作用。 - Soheil Setayeshi
3个回答

7
你的程序没有 --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();
}

希望这能帮助到您。

但是如果执行后还有其他选项,我会更满意 :D - Soheil Setayeshi
1
当然,在执行后还有一种更复杂的方法,我将扩展我的答案。 - salocinx

2
Runtime r=Runtime.getRuntime();
process p=r.exec("your string");

尝试这种方法。

1

1
这个问题是关于在进程开始执行之后向其提供数据,而不是命令行参数的问题。 - Bernhard Barker
1
@Dukeling:密码几乎可以作为参数传递。 - salocinx

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接