0

我正在使用运行时执行一个命令,该命令接受两次密码(例如:输入密码,验证密码)。我正在使用以下代码。我面临的问题是程序挂起,因为它正在等待验证密码。第一个密码被正确传递(我通过从我的命令和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);


    }
4

2 回答 2

0

两者while ((inLine = stdin.readLine()) != null) {都会while ((errLine = stderr.readLine()) != null) {阻塞你的主线程,直到数据可用。可能是您的命令将某些内容吐出到 stderr 但您看不到它,因为您的主线程在 stdin 读取循环中被阻塞

最好使用单独的线程使用 stdin 和 stderr,您可以更轻松地调试代码

于 2013-06-25T06:30:26.740 回答
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.
    }
}

重复那个

<<验证密码>>

并更改变量。那应该工作!

这是验证密码

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.
    }
}
于 2013-06-25T06:32:07.000 回答