Compile and run a java program through another one
Hi all,
I want to compile and run some run-time generated java code via another one, consider for example the following program:
Code:
public class Test {
public static void main(String[] args) throws IOException {
FileOutputStream fos = new FileOutputStream("src/JavaProgram0.java");
String s = "\npublic class JavaProgram0 {\n" +
" public void print() {System.out.println(\"first\");\n }\n}";
fos.write(s.getBytes());
fos.close();
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
int result = compiler.run(null, null, null,"src/JavaProgram0.java");
JavaProgram0 j = new JavaProgram0();
j.print();
}
}
in this code i write a very simple program defined by a string, to a file and then compile and run it.
it is Ok for one program but if i extend it to compile and run more than one programs it just runs the first one :
Code:
public class Test {
public static void main(String[] args) throws IOException {
FileOutputStream fos = new FileOutputStream("src/JavaProgram0.java");
String s = "\npublic class JavaProgram0 {\n" +
" public void print() {System.out.println(\"first\");\n }\n}";
fos.write(s.getBytes());
fos.close();
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
int result = compiler.run(null, null, null,"src/JavaProgram0.java");
JavaProgram0 j = new JavaProgram0();
j.print();
FileOutputStream fos1 = new FileOutputStream("src/JavaProgram0.java");
String s1 = "\npublic class JavaProgram0 {\n" +
" public void print() {System.out.println(\"second\");\n }\n}";
fos1.write(s1.getBytes());
result = compiler.run(null, null, null,"src/JavaProgram0.java");
JavaProgram0 j2 = new JavaProgram0();
j2.print();
}
}
in the above example "first" "first" is printed but it is intended to print "first" "second"!
do you have any idea to address this problem?
Thanks in advance,
Z.Zojaji