Java calls shell commands and scripts

Source: Internet
Author: User

Shell scripts are powerful and simple when working with text and managing the operating system.
Combining shell scripts into your application is a great way to quickly implement
This article describes the use of Java code to invoke and execute the shell

I wrote jbosslogdelivery.sh in the ~/bin/directory, with two features.
The {./jbosslogdelivery.sh list} function is to output the list of existing JBoss logs,
{./jbosslogdelivery.sh get LogName [email protected]} is the role of sending the specified log to the specified mailbox

I intend to integrate this script in a Web application to operate the script via HTTP GET.
Here is the core code

It is recommended to use Processbuilder to create a processing process, the parameter cmds is a string array,
One way to get popular online is runtime.getprocess, I'm testing my own directory when I execute a script.
According to the above script, the output log list function Cmds The value {"jbosslogdelivery.sh", "list"}
The CMDS value of the Extract log function is {"jbosslogdelivery.sh", "Get", "logname", "[Email protected]"}
Processbuilder processbd=new Processbuilder (CMDS);
Switch to the directory where the script is located
Processbd.directory (New File (ScriptPath)); ScriptPath = "~/bin/";
Start execution
Process = Processbd.start ();
Execution results
int status = Process.waitfor ();
Read the output of the script
br = new BufferedReader (New InputStreamReader (Process.getinputstream ()));
Processing results
String line = "";
while (line =br.readline ())!=null) {
Reslist.add (line);
}

Java calls shell commands and scripts

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.