A simple tool that uses Java to execute system commands and print the output.
Public class osexecute <br/>{< br/>/** <br/> * <B> command. </B> <br/> * <p> <B> Description: </B> </P> <br/> * <! -- Add a detailed description here --> <br/> * none. <Br/> * @ Param command <br/> */<br/> Public static void command (string command) {<br/> try <br/> {<br/> Process = new processbuilder (arrays. aslist (command. split (""))). start (); <br/> // standard input stream <br/> bufferedreader result = new bufferedreader (New inputstreamreader (process. getinputstream (); <br/> string S = result. readline (); <br/> while (s! = NULL) {<br/> system. out. println (s); <br/> S = result. readline (); <br/>}< br/> // standard error input stream <br/> bufferedreader error = new bufferedreader (New inputstreamreader (process. geterrorstream (); <br/> S = error. readline (); <br/> while (s! = NULL) {<br/> system. err. println (s); <br/> S = error. readline (); <br/>}< br/>}catch (exception e) <br/>{< br/> // correct <br/> If (! Command. startswith ("CMD/C") {<br/> command ("CMD/C" + command ); <br/>} else {<br/> throw new runtimeexception (E. getmessage (); <br/>}< br/> Public static void main (string [] ARGs) {<br/> osexecute. command ("dir"); <br/>}< br/>}
Test ls (test in Windows). Command result:
The volume in drive E is Doc
The serial number of the volume is the B411-2480
E:/workspace/Java/thinkinjava/book directory
2010/12/28 20:30 <dir>.
2010/12/28 20:30 <dir> ..
2010/12/28 518. classpath
2010/08/29 380. Project
2010/12/28 17:09 <dir>. Settings
2010/12/28 19:57 <dir> Bin
2010/12/28 100 data.txt
2010/08/29 09:02 <dir> Source
2010/12/28 :55 <dir> SRC
2010/08/29 <dir> Test
3 files in 998 bytes
13,018,263,552 bytes available for 7 Directories