我需要在我的 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/