Executing shell commands/Scripts from Java code

Source: Internet
Author: User
Tags getmessage

There are two ways that the JDK comes with the runtime.getruntime (). EXEC () and Processbuilder classes, which are introduced after JDK1.5, and are also recommended by the authorities to abandon the use of runtime. Today in the implementation of the time is to use the Processbuilder,apache Commons Class library also provides an exec package specifically to do this kind of function, this time is useless.

During the writing process, there are several places where the pits are compared:

1. The parameters used in building Processbuilder:

It is recommended to use "/bin/bash". "-C", "your shell" to assemble a list, in fact, if you execute more than one command at a time, you can be unified into the "your shell" string.

2. Output flow control during execution:

In the execution process, we certainly need to get the normal execution results, but also need to know the content of the error prompt, then need to redirect the error output stream to the standard output stream, equivalent to the combined output

3, some commands are required to support the environment variables, it is necessary to execute the evivonment () copy system-related env variable into the current process context for the command to use.

4, if the execution process is dead, you need to know which process can kill, so the output will print the current process ID, easy to handle manually.


The complete code is as follows:

  public int execmd (String shell) throws IOException {int success = 0;    StringBuffer sb = new StringBuffer ();    BufferedReader br = null;    Get name representing the running Java virtual machine.    String name = Managementfactory.getruntimemxbean (). GetName ();    String pid = Name.split ("@") [0]; try {System.out.println ("starting to exec{" + Shell + "}.      PID is: "+ pid";      Process process = NULL;      Processbuilder PB = new Processbuilder ("/bin/bash", "-C", Shell);      Pb.environment (); Pb.redirecterrorstream (TRUE);      Merge error stream into the standard stream process = Pb.start ();        if (process! = null) {br = new BufferedReader (New InputStreamReader (Process.getinputstream ()), 1024);      Process.waitfor ();      } else {System.out.println ("There is no PID found.");      } sb.append ("Ending exec right now, the result is:\n");      String line = null; while (BR! = null && (line = Br.readline ()) = null){Sb.append (line). append ("\ n"); }} catch (Exception IoE) {sb.append ("Error occured when exec cmd:\n"). Append (Ioe.getmessage ()). Append (    "\ n");      } finally {PrintWriter writer = null;      if (br! = null) {br.close ();        } try {writer = new PrintWriter (System.out);      Writer.write (Sb.tostring ());      } catch (Exception e) {log.error (E.getmessage (), E);      } finally {writer.close ();    } success = 1;  } return success; }


Executing shell commands/Scripts from Java code

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.