Using Runtime#exec() with javac - No Class

2019-09-02 03:23发布

问题:

The following MyCompilingUtility.java creates a file (a Java class - AutoGenerated.java) via a PrintWriter. This class only has a Main method with a print statement. Secondly, this program calls javac AutoGenerated.java.

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();
}

However, after running javac MyCompilingUtility.java && java MyCompilingUtility, there's no AutoGenerated.class file produced.

Why is that?

回答1:

You're missing a ; at the end of

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

The compiler simply fails to compile it.



标签: java runtime