2014-02-05 54 views
0

以下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文件。

這是爲什麼?

+0

從exec()中獲取'Process'並調用它的'waitFor'方法。它返回什麼代碼? –

+0

我應該閱讀文檔。 @SotiriosDelimanolis。運行'waitFor'返回1.這些文檔(http://docs.oracle.com/javase/7/docs/api/java/lang/Process.html#waitFor())表示'0'表示正常完成。 –

回答

1

你在

writer.println(" System.out.println(\"Hello from AutoGenerated World\");"); 
                     ^

末編譯器只是無法編譯它缺少一個;

+1

@KevinMeredith爲了將來的參考,重現步驟:運行你的代碼,修改它來添加檢查退出代碼,讀取錯誤'InputStream'('Process#getErrorStream()'),並且確切地說出了問題。 –