AF
HomeTagSubmit NotesAsk AnythingLoginSubscribe Us
AF
1. Feel Free to ask and submit anything on Anyforum.in and get satisfactory answer
2. Registration is not compulsory, you can directly login via google or facebook
3. Our Experts are looking for yours ?.



java-compiler: How to compile and run java program by java code?

I want to compile a .java file by another java program. Please give me a sample program.

java x 211
compiler x 5
Posted On : 2014-11-18 12:26:33.0
profile Garima Gupta - anyforum.in Garima Gupta
596129558962
up-rate
5
down-rate

Answers


You can use Runtime class's method to execute the command like javac, java, etc. For example:
Process pro = Runtime.getRuntime().exec(command);
Where command is the String type argument, its value may be like "javac filename.java", "java class_name"

Following is the working program to Compile and run another java file. Suppose we have a java file named Main.java and we need to compile and run this file. Its source code is like following:

Main.java:
----------------------------------
public class Main {
public static void main(String[] args) {
System.out.println("This is Main class.");
}
}


And following is the java source code to compile and run the above file:


JavaCompiler.java:
-------------------------------------------
import java.io.*;

public class JavaCompiler {

private 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 int runProcess(String command) throws Exception {
Process pro = Runtime.getRuntime().exec(command);
printLines(command + " stdout:", pro.getInputStream());
printLines(command + " stderr:", pro.getErrorStream());
pro.waitFor();
return pro.exitValue();
}

public static void main(String[] args) {
try {
System.out.println("Compiling by javac Main.java....");
int k = runProcess("javac Main.java");
if (k==0){
System.out.println("Compiled Successfully....");
System.out.println("Running by java Main....");
k=runProcess("java Main");
}
} catch (Exception e) {
e.printStackTrace();
}
}
}


Now you just have to compile and run only JavaCompiler.java file by command prompt.
Output:
==========================
Java Compiler Output

Download this example- Click Here

Posted On : 2014-11-18 12:58:41
Satisfied : 1 Yes  0 No
profile Rishi Kumar - anyforum.in Rishi Kumar
523188249150
Reply This Thread
up-rate
5
down-rate



Post Answer
Please Login First to Post Answer: Login login with facebook - anyforum.in