0

I am trying the following code to compile an external C program with a Java program

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public static void main(String[] args){
    try{
        Runtime rt=Runtime.getRuntime();
        Process pr=rt.exec("cmd /c PATH=%PATH%;c:\\TC\\BIN");
        pr=rt.exec("cmd /c c:\\TC\\BIN\\TCC.exe c:\\TC\\EXAMPLE.c");
        pr=rt.exec("c:\\TC\\EXAMPLE.exe");
        BufferedReader input=new BufferedReader(new InputStreamReader(pr.getInputStream()));
        String line=null;

        while((line=input.readLine())!=null){
            System.out.println(line);
        }
        int exitVal=pr.waitFor();
        System.out.println("exited with error code "+exitVal);
    }
    catch(Exception e){
        System.out.println(e.toString());
        //e.printStackTrace();
    }
}
}

but I am getting:

java.io.IOException: Cannot run program "c:\TC\EXAMPLE.exe": CreateProcess error=2, The system cannot find the file specified

The compilation process is not working, so what else can I do to compile my C code?

devrys
  • 1,571
  • 3
  • 27
  • 43

2 Answers2

3

Please use the Processbuilder API for this, The documentation has an example of how to use the various flags.

JVXR
  • 1,294
  • 1
  • 11
  • 20
1

I think that you are calling the compiled program before it had the chance to be generated. You should wait on the call:

pr=rt.exec("cmd /c c:\\TC\\BIN\\TCC.exe c:\\TC\\EXAMPLE.c");

To finish before you try calling the compiled output.

JTMon
  • 3,189
  • 22
  • 24
  • so do i need to use some wait command to make the same program able to compile and execute the code? – user1617085 Sep 09 '12 at 16:53
  • You can just call rt.waitFor() It will wait for the process to end and gives you the exit value of the thread. – JTMon Sep 09 '12 at 16:58