How to execute shell script in Java?

Source: Internet
Author: User

It is often necessary to call other scripts (shell, CMD) in Java, which were used previously:

Runtime r = runtime. getsystemruntime (); <br/> r.exe C ("whatever you want to run "); 

However, sometimes the running results are unpredictable, causing a lot of trouble. After Java 5.0, processbuilder to create operating system processes is introduced:

String cmd = "CD.../; LS-L"; // This is the command to execute in the Unix shell <br/> cmd = "CD ~ /Kaven/tools/Dart; SH start_dart.sh "; <br/> // create a process for the shell <br/> processbuilder Pb = new processbuilder (" bash ", "-c", CMD); <br/> Pb. redirecterrorstream (true); // use this to capture messages sent to stderr </P> <p> process shell = Pb. start (); <br/> inputstream shellin = shell. getinputstream (); // This captures the output from the command <br/> int shellexitstatus = shell. waitfor ();// Wait for the shell to finish and get the return code </P> <p> // At this point you can process the output issued by the command <br/> // for instance, this reads the output and writes it to system. out: <br/> int C; <br/> while (C = shellin. read ())! =-1) {<br/> system. out. write (c); <br/>}< br/> // close the stream <br/> try {<br/> shellin. close (); <br/>}< br/> catch (ioexception ignoreme) <br/>{}< br/> system. out. print ("*** end ***" + shellexitstatus); </P> <p> system. out. println (Pb. command (); <br/> system. out. println (Pb. directory (); <br/> system. out. println (Pb. environment (); <br/> system. out. println (system. getenv (); <br/> system. out. println (system. getproperties ()); 

Related Article

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.