以下MyCompilingUtility.java
通過PrintWriter
創建一個文件(Java類 - AutoGenerated.java
)。這個類只有一個帶有打印語句的Main方法。其次,這個程序調用javac AutoGenerated.java
。使用帶有javac的Runtime#exec() - 無類文件
public static void main(String args[]) throws IOException,
FileNotFoundException, UnsupportedEncodingException {
createFile("AutoGenerated.java");
compile("AutoGenerated.java");
}
public static void compile(String fileName) throws IOException {
final String javacPath = "C:/Program Files/Java/jdk1.7.0_51/bin/javac.exe";
Runtime rt = Runtime.getRuntime();
final String compileCmd = javacPath + " " + fileName;
rt.exec(compileCmd);
}
public static void createFile(String fileName) throws FileNotFoundException,
UnsupportedEncodingException {
PrintWriter writer = new PrintWriter(fileName, "UTF-8");
writer.println("public class AutoGenerated");
writer.println("{");
writer.println(" public static void main(String [] args)");
writer.println(" {");
writer.println(" System.out.println(\"Hello from AutoGenerated World\")");
writer.println(" }");
writer.println("}");
writer.close();
}
但是,運行javac MyCompilingUtility.java && java MyCompilingUtility
後,有沒有產生AutoGenerated.class
文件。
這是爲什麼?
從exec()中獲取'Process'並調用它的'waitFor'方法。它返回什麼代碼? –
我應該閱讀文檔。 @SotiriosDelimanolis。運行'waitFor'返回1.這些文檔(http://docs.oracle.com/javase/7/docs/api/java/lang/Process.html#waitFor())表示'0'表示正常完成。 –