Java executes the .exe file. Here, Java calls g ++ to compile a program.
(My g ++ compiler and programs are in the directory H:/bin/GCC/bin)
Let's first look at the program:
Package Wen. hui; </P> <p> Import Java. io. bufferedreader; <br/> Import Java. io. inputstream; <br/> Import Java. io. inputstreamreader; </P> <p> public class testexec {</P> <p> Public static void main (string [] ARGs) {</P> <p> testexec javaexec = new testexec (); <br/> javaexec. testprocess (); <br/>}</P> <p> Public void testprocess () {<br/> try {</P> <p> string Path = "H: // bin // GCC // bin //"; <br/> string command = path + "G + +-O "+ path +" test.exe "+ path +" test. C "; <br/> Process = runtime.getruntime(cmd.exe C (command ); </P> <p>/* <br/> * testinputstream errorstream = new testinputstream (Process <br/> *. geterrorstream (); errorstream. start (); <br/> */</P> <p> string line = NULL; </P> <p> // get the process's errorstream <br/> inputstream errorstream = process. geterrorstream (); <br/> bufferedreader reader = new buffere Dreader (New inputstreamreader (errorstream); </P> <p> system. out. println ("----------------- error informaiton ------"); <br/> while (line = reader. readline ())! = NULL) {<br/> system. out. println (line); <br/>}< br/> system. out. println ("--------------- error informaiton ------/N"); </P> <p> int exitvalue = process. waitfor (); <br/> system. out. println ("Return Value:" + exitvalue); <br/> reader. close (); <br/> errorstream. close (); <br/> process. destroy (); </P> <p >}catch (exception e) {<br/> system. out. println ("exception .... "); <br/>}</P> <p >}< br/>
Here is only a demonstration. In actual use, absolute paths should not be used ....
Now let's explain the above program,
In fact, it is very simple. First, write a command, such as G ++ to compile the. C program. The command is: G ++-O test.exe test. c
Runtime. getruntime,
Then call its exec (CMD) method, which returns a process Process
You can see from the process API that process has only a few methods, but it is very useful as follows:
abstract void |
destroy() Kill the child process. |
abstract int |
exitValue() Returns the export value of the sub-process. |
abstract InputStream |
getErrorStream() Obtain the error stream of the sub-process. |
abstract InputStream |
getInputStream() Obtain the input stream of the sub-process. |
abstract OutputStream |
getOutputStream() Obtain the output stream of the sub-process. |
abstract int |
waitFor() Cause the current thread to wait. If necessary, wait untilProcess The process indicated by the object has been terminated. |
Here, only the information is read from the error stream. If the compilation is incorrect (as can be seen from the return value), the error information will be displayed...