简体   繁体   中英

Programmatically compiling .java files, error

When run this code to compile a .java file in this directory:

String title = txtName.getText();
        String name = title + ".Java";
        String src = Minecraft.getMinecraft().mcDataDir.getParent().toString() + "/saves/" + world.getWorldInfo().getWorldName().toString() + "/TechRev/Compiler/";
        compile(src + name);

With this method:

public void compile(String file) {
    String fileToCompile = file;
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    int compilationResult = compiler.run(null, null, null, fileToCompile);
    if (compilationResult == 0) {
        System.out.println("Compilation is successful");
    } else {
        System.out.println("Compilation Failed");
    }
}

I get this error in the console of Eclipse Juno(Java 6):

2013-10-02 20:47:47 [INFO] [STDERR] javac: invalid flag: /Users/marko5049/Desktop/Modding/forge/mcp/jars/saves/TechRev/TechRev/Compiler/TechRev.Java
2013-10-02 20:47:47 [INFO] [STDERR] Usage: javac <options> <source files>
2013-10-02 20:47:47 [INFO] [STDERR] use -help for a list of possible options
2013-10-02 20:47:47 [INFO] [STDOUT] Compilation Failed

Please could someone explain to me why this is happening and show me how to fix this? thanks!

-Regards Mark

Your filename ends with .Java - it should be .java . Otherwise the compiler doesn't expect it to be a source file, and tries to process it as a flag instead.

.java not .Java

String name = title + ".Java";

change this to

`String name = title + ".java"`;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM