import java.io.*;
public class Auto {
/**
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
try {
Runtime.getRuntime().exec("javac C:/HelloWorld.java");
Runtime.getRuntime().exec("java C:/HelloWorld > C:/out.txt");
System.out.println("END");
} catch (IOException e) {
e.printStackTrace();
}
}
}
This program is able to compile the ‘HelloWorld.java’ file, but not execute it(HelloWorld).
Could anyone please suggest me how to make it work?
Thanks in Advance! 🙂
Also, if the output could be able to be taken in another text file say ‘output.txt’.
When your run the
javaprogram, you must be in your project root directory, and runjava package.to.ClassWhichContainsMainMethodRuntime.getRuntime().exec()will give you aProcesswhich contains anOutputStreamand anInpuStreamto the executed application.You can redirect the
InputStreamcontent to your log file.In your case I would use this exec :
public Process exec(String command, String[] envp, File dir)like this :To copy data from the inputStream to the file (code stolen on this post) :