简体   繁体   中英

How to compile a Java program using another program?

all am working a project for compiling and running a java source code via my application. here am stuck will explain my environment here.. java 1.6.0_35 32bit and eclipse indigo using operating system windows 64 bit
when i used this code

String command = "javac "+file.getAbsolutePath();
System.out.println(command);
Process p = Runtime.getRuntime().exec(command);`

got this exception ..think error show file doesnt exist but i checked it,which is here and when i execute via command line which compiles,but the eclipse shows this error

java.io.IOException: Cannot run program "javac": CreateProcess error=2, The system cannot find the file specified
at java.lang.ProcessBuilder.start(Unknown Source)
at java.lang.Runtime.exec(Unknown Source)
at java.lang.Runtime.exec(Unknown Source)
at java.lang.Runtime.exec(Unknown Source)`

can anyone fix this ,i tried a lot ..

You don't need to use the command line, you can access javac programmatically:

JavaCompiler javac = ToolProvider.getSystemJavaCompiler();
javac.run(null, null, null, arguments);

See

It is portable (works on other systems) and will avoid problems with paths and command line.

You can use Java 6 Compiler API . Also this link might be useful..

Your problem seems not so much that the file you want to compile is not found, but that the javac command itself is not found. Make sure that the Runtime can find the javac executable, eventually by passing the "PATH=/path/to/java/dir" to exec.

See: Runtime.exec(command, enviroment, dir)

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