Calling external commands in Java

Source: Internet
Author: User
Tags return string
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;}} }

Related Article

Alibaba Cloud 10 Year Anniversary

With You, We are Shaping a Digital World, 2009-2019

Learn more >

Apsara Conference 2019

The Rise of Data Intelligence, September 25th - 27th, Hangzhou, China

Learn more >

Alibaba Cloud Free Trial

Learn and experience the power of Alibaba Cloud with a free trial worth $300-1200 USD

Learn more >

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: and provide relevant evidence. A staff member will contact you within 5 working days.