Hi there,
I am new to this forum. First post here. I've been working on a code lately that compiles and executes another main class:
CompilerMaster.java :
package compilermaster; import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; public class CompilerMaster { public static void printLines(String name, InputStream ins) throws Exception { String line = null; BufferedReader in = new BufferedReader( new InputStreamReader(ins) ); while ((line = in.readLine()) != null) { System.out.println(name + " " + line); } } private static void runProcess(String command) throws Exception { Process pro = Runtime.getRuntime().exec(command); // <------------- this executes cmd lines printLines(command + " stdout:", pro.getInputStream()); // <------------- Gets info if it worked printLines(command + " stderr:", pro.getErrorStream()); // <------------- Gets info on any errors pro.waitFor(); System.out.println(command + " exitValue() " + pro.exitValue()); } public static void main(String[] args) { try { runProcess("javac Test.java"); runProcess("java Test"); } catch (Exception e) { e.printStackTrace(); } } }
Test.java:
package compilermaster; public class Test { public static void main(String[] args) { System.out.println("ok"); } }
Output:
In theory, the program should be printing "ok".run:
javac Test.java stderr: javac: file not found: Test.java
javac Test.java stderr: Usage: javac <options> <source files>
javac Test.java stderr: use -help for a list of possible options
javac Test.java exitValue() 2
java Test stderr: Error: Could not find or load main class Test
java Test exitValue() 1
BUILD SUCCESSFUL (total time: 1 second)
Additional Notes: I am using NetBeans IDE 7.3.1, classes are saved in the same location. If you substitute any of the commands with "dir" it doesn't work. Also tried adjust the cmd location using "cd (file location)" and did not work.