Calling external commands in Java

Source: Internet
Author: User
Calling external commands in Java execcommond{public Execcommond () {}/** * executing a command * @param execstr string Command strings * @return string The information when the command error is executed. */public static string exec (String execstr) {Runtime Runtime = Runtime.getruntime (); Get current Run-time object String outinfo= "";//Execute Error The output information try {string[] args = new string[] {"sh", "-C", execstr};//execute commands under Linux//execute commands under Windows//string[] args = new String [] {"cmd", "-C", execstr}; Process proc = runtime.exec (args); Start another process to execute the command inputstream in = Proc.geterrorstream ();//Get the error message output. BufferedReader br = new BufferedReader (new InputStreamReader (in)); String line = ""; while (line = Br.readline ())!= null) {Outinfo = outinfo + line + \ n; System.out.println (Outinfo); //Check to see if the command failed.  try {if (proc.waitfor ()!= 0) {System.err.println ("exit value =" + Proc.exitvalue ());}} catch (Interruptedexception e) {System.err.print (e); E.printstacktrace ();}} catch (IOException e) {flag = false; SYSTEM.OUT.PRINTLN ("Exec error:" + e.getmessage ()); E.printstacktrace ();finally {return outinfo;}} }



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.