2015-04-23 47 views
2

我想編寫一個程序來執行JAR並獲取它們的輸出。 當JAR程序只有一個打印語句時它可以正常工作,但是當它在執行過程中要求輸入時,程序會凍結。通過Java進程將輸入發送到正在運行的JAR

代碼的JAR文件程序:

public class jartorun { 
    public static void main(String arg[]) throws IOException { 
     String t = "javaw -jar D:\\jarcheck\\temp.jar"; 
     Process p = Runtime.getRuntime().exec(t); 
     BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream())); 
     String line = ""; 
     while ((line = input.readLine()) != null) { 
      System.out.print(line + "\n"); 
     } 
     input.close(); 
    } 
} 

我可以使用process.getOutputStream()給輸入JAR,但我會​​怎樣:

import java.util.*; 

public class demo { 

    public static void main(String r[]) { 
     Scanner sc = new Scanner(System.in); 
     System.out.println("Hello ..."); 
     System.out.println("please enter the number :"); 
     int i = sc.nextInt(); 
     System.out.println(" number : " + i); 

    } 
} 

它運行的JAR文件的原始程序代碼使用它,所以我可以創建一個程序,可以給JAR輸入並同時讀取其輸出?

+0

你爲什麼從Java運行'jar'?爲什麼不把它加載到類路徑中並簡單地調用該方法?此外,如果您選擇從Java運行外部程序,請使用新的['ProcessBuilder'](http://stackoverflow.com/questions/6856028/difference-between-processbuilder-and-runtime-exec)而不是'Runtime .exec'。 –

回答

0

如果你想運行虛擬機之外的東西,請使用ProcessBuilder。對我來說工作得很好,你可以繼承IO Stream。

ProcessBuilder builder = new ProcessBuilder("./script.sh", 
          "parameter1"); 
      builder.directory(new File("/home/user/scripts/")); 
      builder.inheritIO(); 

      try { 
        Process p = builder.start(); 
        p.waitFor(); 
        // Wait for to finish 
      } catch (InterruptedException e) { 
        e.printStackTrace(); 
      } catch (IOException ioe) { 
        ioe.printStackTrace(); 
      } 

這應該也適用於Windows批處理腳本和路徑。 (還沒有嘗試輸入)

0

您可以使用p.getOutputStream()爲啓動的過程提供輸入。

相關問題