我需要在我的Java程序中执行一个命令,但在执行完命令后,它需要另一个参数(在我的情况下是密码)。如何管理Runtime.getRuntime().exec()
的输出过程以接受用于进一步执行的参数?
我尝试了new BufferedWriter(new OutputStreamWriter(signingProcess.getOutputStream())).write("123456");
,但没有起作用。
我需要在我的Java程序中执行一个命令,但在执行完命令后,它需要另一个参数(在我的情况下是密码)。如何管理Runtime.getRuntime().exec()
的输出过程以接受用于进一步执行的参数?
我尝试了new BufferedWriter(new OutputStreamWriter(signingProcess.getOutputStream())).write("123456");
,但没有起作用。
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();
}
Runtime r=Runtime.getRuntime();
process p=r.exec("your string");
如果您在Windows上工作,应该在参数中提供您的Windows命令
访问此链接以获取更多详细信息:http://docs.oracle.com/javase/6/docs/api/java/lang/Runtime.html