Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compile and run source code from Java application

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 could I accomplish that?

like image 726
Kenny Meyer Avatar asked Oct 24 '22 15:10

Kenny Meyer


2 Answers

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

like image 134
shababhsiddique Avatar answered Oct 27 '22 09:10

shababhsiddique


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

like image 35
Senthil Avatar answered Oct 27 '22 10:10

Senthil