Compile and run source code from a Java application

I need to compile and run the source code (separate file) written in Python, Pascal or C from my Java application.

I need to know:

  • If the compilation process was successful
  • compiled program return

How could I do this?

+5
source share
5 answers

I did the same.

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;                      
       }  

These are 2 functions used in my first MiDE, which was used for compilation. Change the address to the place of the compiler. and returns a log (if compilation fails) to see errors.

The second runs the compiled code. Return the exit code to verify that it completed correctly.

Java-. , ;).. , , .

+1

, Process, ( , ), Runtime.getRuntime().exec(), ProcessBuilder, Process ( , , , ProcessBuilder, , ). ( ), .

:

http://www.rgagnon.com/javadetails/java-0014.html

Process, waitFor(). , - .

+1
source

You probably want to use Runtime.exec()to call the appropriate compiler. Check out the JavaDoc for more information on how to handle output, etc.

0
source

If you mostly make snippets of code, you can try running Python code using Jython. See Howto multithreaded jython scripts running from java for more details. .

0
source

All Articles