Test.java
package com.journaldev.files; public class Test { public static void main(String[] args) { System.out.println("Start"); for(String str : args){ System.out.println(str); } } }
CompileRunJavaProgram.java
package com.journaldev.files; import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; public class CompileRunJavaProgram { public static void main(String[] args) { try { runProcess("pwd"); System.out.println("**********"); runProcess("javac -cp src src/com/journaldev/files/Test.java"); System.out.println("**********"); runProcess("java -cp src com/journaldev/files/Test Hi Pankaj"); } catch (Exception e) { e.printStackTrace(); } } private static void printLines(String cmd, InputStream ins) throws Exception { String line = null; BufferedReader in = new BufferedReader( new InputStreamReader(ins)); while ((line = in.readLine()) != null) { System.out.println(cmd + " " + line); } } private static void runProcess(String command) throws Exception { Process pro = Runtime.getRuntime().exec(command); printLines(command + " stdout:", pro.getInputStream()); printLines(command + " stderr:", pro.getErrorStream()); pro.waitFor(); System.out.println(command + " exitValue() " + pro.exitValue()); } }
运行结果:
pwd stdout: /Users/pankaj/CODE/JavaPrograms pwd exitValue() 0 ********** javac -cp src src/com/journaldev/files/Test.java exitValue() 0 ********** java -cp src com/journaldev/files/Test Hi Pankaj stdout: Start java -cp src com/journaldev/files/Test Hi Pankaj stdout: Hi java -cp src com/journaldev/files/Test Hi Pankaj stdout: Pankaj java -cp src com/journaldev/files/Test Hi Pankaj exitValue() 0
转自:http://www.journaldev.com/937/how-to-compile-and-run-java-program-in-another-java-program