Java command execution (CMD, shell)

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.