I need to compile and run source code (single file), written in Python, Pascal or C, from my Java application.
I will need to know:
- if compile process was successful
- the return output of the compiled program
How co开发者_JS百科uld I accomplish that?
I have been doing the same thing..
public String compile()
{
String log="";
try {
String s= null;
//change this string to your compilers location
Process p = Runtime.getRuntime().exec("cmd /C \"C:\\Program Files\\CodeBlocks\\MinGW\\bin\\mingw32-g++.exe\" temp.cpp ");
BufferedReader stdError = new BufferedReader(new
InputStreamReader(p.getErrorStream()));
boolean error=false;
log+="\n....\n";
while ((s = stdError.readLine()) != null) {
log+=s;
error=true;
log+="\n";
}
if(error==false) log+="Compilation successful !!!";
} catch (IOException e) {
e.printStackTrace();
}
return log;
}
public int runProgram()
{
int ret = -1;
try
{
Runtime rt = Runtime.getRuntime();
Process proc = rt.exec("cmd.exe /c start a.exe");
proc.waitFor();
ret = proc.exitValue();
} catch (Throwable t)
{
t.printStackTrace();
return ret;
}
return ret;
}
This are 2 functions used in my MiDE first one used to compile. Change the address to your compilers location. and returns the log(in case compilation was failed) to see the errors.
The 2nd one runs the compiled code. Returning the exit code to check whether it terminated correctly.
I am not a very good java coder . i guess you can improve my code a lot better ;) .. in case you do please inform me. And i am also looking for a answer on how to communicate with the created process
You could use java.lang.ProcessBuilder to execute commands and check the status. Here JAVADOC : http://download.oracle.com/javase/1.5.0/docs/api/java/lang/ProcessBuilder.html
In general, you'll want to launch a Process
that runs the external program (first the compiler, and then the compiled binary in your case), using either Runtime.getRuntime().exec()
or a ProcessBuilder
to spawn the Process
(since your compiler probably takes a complicated set of options, the ProcessBuilder
is likely a better option). This will allow you to grab the output from the process as it executes (so you can monitor the compiler output for warnings or errors), as well as its return code.
You may find the following examples helpful:
http://www.rgagnon.com/javadetails/java-0014.html
To get the return code of a running Process
, just use the waitFor()
method. This is convenient if you don't care about any of the output and just want the return value.
You're probably going to want to use Runtime.exec()
to call the respective compiler. Check out the JavaDoc for more information about how to deal with the output, etc.
If you're mainly doing code snippets you might try running Python code using Jython. See Howto multithreaded jython scripts running from java? for details.
精彩评论