2017-06-01 35 views
0

我想使用流程構建器運行Windows命令。我不確定它爲什麼會退出1,因爲我覺得我給了正確的輸入。如果任何人都能看到它並指導我可能會出錯的地方,那將是非常棒的。流程構建器不接受通過getOutputStream輸入

try{ 
      ProcessBuilder pb = new ProcessBuilder("runas","/noprofile","/user:alex", "cmd"); 
      Process p = pb.start(); 
      OutputStream os = p.getOutputStream(); 
      PrintStream ps = new PrintStream(os); 
      ps.println("password"); 
      ps.flush(); 

      System.out.println(p.waitFor()); 
      BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream())); 
      String resultLine = in.readLine(); 
      while (resultLine != null) { 
       System.out.println(resultLine); 
      resultLine = in.readLine(); 
      } 
     } 
      catch (IOException e) { 
       e.printStackTrace(); 
      } 

輸出:

亞歷輸入密碼:

+0

檢查錯誤流的錯誤輸出 – Binu

+0

要輕鬆獲取錯誤流,使用'pb.redirectErrorStream(true)'將其重定向到stdout。但[它可能根本不可能](https://stackoverflow.com/q/25664203/6730571)...也許'runas'不接受標準輸入密碼 –

+0

我也試過這個。沒有運氣。不知道爲什麼它返回1作爲退出代碼。 –

回答

0

使用該工具來獲取錯誤

    System.out.println(p.waitFor()); 
        BufferedReader in = new BufferedReader(new InputStreamReader(p.getErrorStream())); 
        String resultLine = in.readLine(); 
        while (resultLine != null) { 
         resultLine = in.readLine(); 
         System.out.println(resultLine);  
        } 
+0

我沒有得到任何東西,如果它運行它。我剛剛得到1爲p.waitfor() –