我正在使用Runtime执行一个命令,该命令接受两次密码(例如:输入密码,验证密码)。我正在使用以下代码。我面临的问题是程序挂起,因为它正在等待验证密码。第一个密码正常传递(我通过从我的命令和java代码中删除验证密码来验证它是否有效),验证密码没有传递给命令,并且命令无限期地等待验证密码。如果有人有任何吸烟,请告诉我。
try
{
runtime = Runtime.getRuntime();
process = runtime.exec("<<my command>>"");
String inLine = "";
String errLine = "";
StringBuffer inBuffer = new StringBuffer();
StringBuffer errBuffer = new StringBuffer();
PrintWriter pw = new PrintWriter(process.getOutputStream());
pw.print("<<password>>"+"\n");
pw.print("<<verify password>>"+"\n");
pw.flush();
BufferedReader stdin = new BufferedReader(new InputStreamReader(
process.getInputStream()));
BufferedReader stderr = new BufferedReader(new InputStreamReader(
process.getErrorStream()));
while ((inLine = stdin.readLine()) != null) {
inBuffer = inBuffer.append(inLine + "\n");
}
stdin.close();
System.out.println("Output messages of cmd " + inBuffer.toString());
while ((errLine = stderr.readLine()) != null) {
errBuffer = errBuffer.append(errLine + "\n");
}
stderr.close();
System.out.println("Error messages of cmd " + errBuffer.toString());
process.waitFor();
int exitCode = process.exitValue();
System.out.println("cmd " + " exited with code " + exitCode);
}
答案 0 :(得分:0)
while ((inLine = stdin.readLine()) != null) {
和while ((errLine = stderr.readLine()) != null) {
都会阻止您的主线程,直到数据可用。它可能是你的命令吐出一些东西到stderr但是你看不到它,因为你的主线程被stdin读取循环阻塞了
最好使用单独的线程来使用stdin和stderr,您可以更轻松地调试代码
答案 1 :(得分:0)
尝试使用这些东西:
System.out.println("<<password>>");
String pw;
BufferedReader stdin = new BufferedReader(new InputStreamReader(
System.in));
while ((pw = stdin.readLine()) != null){ //Waits for a reply for the first password
if (pw != ""){
break; //This breaks the loop, and 'pw' is the password entered.
}
}
重复
&LT;&LT; verifypassword&gt;&gt;
并更改变量。这应该有效!
这是验证密码
System.out.println("<<verifypassword>>");
String pw2;
BufferedReader stdin2 = new BufferedReader(new InputStreamReader(
System.in));
while ((pw2 = stdin2.readLine()) != null){ //Waits for a reply for the first password
if (pw2 != ""){
break; //This breaks the loop, and 'pw' is the password entered.
}
}