Home »
Java
» Compiling and Running Java program by using another Java program.
package com.ranga;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
/**
Program: Compiling and Running Java program by using another Java program.
java.lang.Runtime.exec()
*/
public class Main {
public static void main(String[] args) {
System.out.println("I am in Main class begin.");
Process process = null;
try {
process = Runtime.getRuntime().exec("javac Test.java");
System.out.println("Test class successfully compiled.");
} catch (IOException ex) {
ex.printStackTrace();
} catch (Exception ex) {
ex.printStackTrace();
}
try {
process = Runtime.getRuntime().exec("java Test");
printMessage(" stdout:", process.getInputStream());
System.out.println("Test class successfully runned.");
} catch (IOException ex) {
ex.printStackTrace();
}
catch (Exception ex) {
ex.printStackTrace();
}
System.out.println("I am in Main class end.");
} // end main()
private static void printMessage(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);
}
} // end printMessage()
} // end Main class
class Test {
public static void main(String a[]) {
System.out.println("I am in Test class");
}
}
0 comments:
Post a Comment