我想編寫一個程序來執行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輸入並同時讀取其輸出?
你爲什麼從Java運行'jar'?爲什麼不把它加載到類路徑中並簡單地調用該方法?此外,如果您選擇從Java運行外部程序,請使用新的['ProcessBuilder'](http://stackoverflow.com/questions/6856028/difference-between-processbuilder-and-runtime-exec)而不是'Runtime .exec'。 –