Java Execute Linux command method _java

Source: Internet
Author: User

The examples in this article describe how Java executes Linux commands. Share to everyone for your reference. The implementation methods are as follows:

Copy Code code as follows:

public class Streamgobbler extends Thread {

InputStream is;
String type;

Public Streamgobbler (InputStream is, String type) {
This.is = is;
This.type = type;
}

public void Run () {
try {
InputStreamReader ISR = new InputStreamReader (IS);
BufferedReader br = new BufferedReader (ISR);
String line = null;
while (line = Br.readline ())!= null) {
if (Type.equals ("Error")) {
System.out.println ("Error:" + line);
} else {
System.out.println ("Debug:" + line);
}
}
catch (IOException IoE) {
Ioe.printstacktrace ();
}
}
}
private void Shell (String cmd)
{
String[] Cmds = {"/bin/sh", "-C", CMD};
Process process;

Try
{
Process = Runtime.getruntime (). exec (CMDS);

Streamgobbler Errorgobbler = new Streamgobbler (Process.geterrorstream (), "Error");
Streamgobbler Outputgobbler = new Streamgobbler (Process.getinputstream (), "Output");
Errorgobbler.start ();
Outputgobbler.start ();
Try
{
Process.waitfor ();
}
catch (Interruptedexception e)
{
E.printstacktrace ();
}
}
catch (IOException E)
{
E.printstacktrace ();
}
}

Where parameter cmd is a Linux command. Only one command can be executed at a time.

1.Java runtime.exec () Considerations:

① always read the data stream before calling the WAITFOR () method
② always read from the standard error stream before reading the standard output stream

2. The best way to execute system commands is to write a bat file or a shell script.

I hope this article will help you with your Java programming.

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.