Java calls External commands

Source: Internet
Author: User

Import java. Io. ioexception;
Import java. Io. inputstream;
Import java. Io. interruptedioexception;
Import java. Io. outputstream;
Import java. util. Concurrent. brokenbarrierexception;
Import java. util. Concurrent. javasicbarrier;
Import java. util. Concurrent. timeunit;
Import java. util. Concurrent. timeoutexception;

Public class commandrunner {

Private Boolean _ waitforexit = true;
Private string _ command;
Private int _ timeout;

Private inputstream _ stdin;
Private outputstream _ stdout;
Private outputstream _ stderr;

Private Static final int Buf = 4096;

Private int _ xit;

Private throwable _ thrownerror;

Private cyclicbarrier _ barrier;

Public commandrunner (string _ command ){
Super ();
This. _ timeout =-1;
This. _ command = _ command;
Setinputstream (null );
Setstderrorstream (system. Err );
Setstdoutputstream (system. Out );
}

Public int getexitvalue (){
Return _ xit;
}

Public void setcommand (string s ){
_ Command = s;
}

Public String getcommand (){
Return _ command;
}

Public void setinputstream (inputstream is ){
_ Stdin = is;
}

Public void setstdoutputstream (outputstream OS ){
_ Stdout = OS;
}

Public void setstderrorstream (outputstream OS ){
_ Stderr = OS;
}

Public void evaluate (string... ARGs) throws ioexception {
Final string Space = "";
Stringbuilder sb = new stringbuilder (_ command );
SB. append (Space );

Final int length = args. length;
For (INT I = 0; I <length; I ++ ){
String Arg = ARGs [I];
SB. append (ARG );
If (I! = Length-1 ){
SB. append (Space );
}
}
String _ command _ = sb. tostring (). Trim ();
System. Out. println (_ command __);
This.exe C (_ command __);

}

/**
*
* @ Return process exit value (return code) or-1 if timed out.
* @ Throws ioexception
*/
Public int exec (string command) throws ioexception {
Process proc = runtime.getruntime(cmd.exe C (command );
_ Barrier = new cyclicbarrier (3 + (_ stdin! = NULL )? 1: 0 ));

Pullerthread so = new pullerthread ("stdout", Proc. getinputstream (), _ stdout );
So. setdaemon (true );
So. Start ();

Pullerthread Se = new pullerthread ("stderr", Proc. geterrorstream (), _ stderr );
Se. setdaemon (true );
Se. Start ();

Pusherthread Si = NULL;
If (_ stdin! = NULL ){
SI = new pusherthread ("stdin", _ stdin, Proc. getoutputstream ());
Si. setdaemon (true );
Si. Start ();
}

Boolean _ timedout = false;

Long end = 0l;
If (_ timeout <0)
End =-1l;
Else
End = system. currenttimemillis () + _ timeout * 1000;

//
Try {
If (_ timeout <= 0 ){
_ Barrier. Await ();
} Else {
_ Barrier. Await (_ timeout, timeunit. Seconds );
}
} Catch (timeoutexception ex ){
_ Timedout = true;
} Catch (brokenbarrierexception bBE ){
/* Ignore */
} Catch (interruptedexception e ){
/* Ignore */
}

// Tell the IO threads we are finished
If (Si! = NULL ){
Si. Interrupt ();
}
So. Interrupt ();
Se. Interrupt ();

_ Xit =-1;

If (! _ Timedout ){
If (_ waitforexit ){
Do {
Try {
Thread. Sleep (1000l );
_ Xit = Proc. exitvalue ();
} Catch (interruptedexception IE ){
If (thread. interrupted ()){
Break; // stop waiting on an interrupt for this
// Thread
} Else {
Continue;
}
} Catch (illegalthreadstateexception iltse ){
Continue;
}
Break;
} While (end <0l) |! (_ Timedout = (system. currenttimemillis ()> end )));
} Else {
Try {
_ Xit = Proc. exitvalue ();
} Catch (illegalthreadstateexception iltse ){
_ Timedout = true;
}
}
}

If (_ waitforexit ){
Proc. Destroy ();
}
Return _ xit;
}

Public throwable getthrownerror (){
Return _ thrownerror;
}

Private class pumperthread extends thread {

Private outputstream _ OS;
Private inputstream _ is;

Private Boolean _ closeinput;

Protected pumperthread (string name, inputstream is, outputstream OS, Boolean closeinput ){
Super (name );
_ Is = is;
_ OS = OS;
_ Closeinput = closeinput;
}

Public void run (){
Try {
Byte [] Buf = new byte [Buf];
Int READ = 0;
While (! Isinterrupted () & (read = _ is. Read (BUF ))! =-1 ){
If (read = 0)
Continue;
_ OS. Write (BUF, 0, read );
_ OS. Flush ();
}
} Catch (interruptedioexception iioe ){
// Ignored
} Catch (throwable t ){
_ Thrownerror = T;
} Finally {
Try {
If (_ closeinput ){
_ Is. Close ();
} Else {
_ OS. Close ();
}
} Catch (ioexception IOE ){
/* Ignore */
}
}
Try {
_ Barrier. Await ();
} Catch (interruptedexception IE ){
/* Ignore */
} Catch (brokenbarrierexception bBE ){
/* Ignore */
}
}
}

Private class pusherthread extends pumperthread {
Pusherthread (string name, inputstream is, outputstream OS ){
Super (name, is, OS, false );
}
}

Private class pullerthread extends pumperthread {
Pullerthread (string name, inputstream is, outputstream OS ){
Super (name, is, OS, true );
}
}

Public int gettimeout (){
Return _ timeout;
}

Public void setTimeout (INT timeout ){
_ Timeout = timeout;
}

Public Boolean getwaitforexit (){
Return _ waitforexit;
}

Public void setwaitforexit (Boolean waitforexit ){
_ Waitforexit = waitforexit;
}

Public static void main (string [] ARGs) throws exception {
Commandrunner Cr = new commandrunner (null );
// Cr. Evaluate ("1", "H: \ Ad-video-auto-find \ 1 H", "C: \ a_auto.txt ",
// "C: \ B _auto.txt ");
Cr. setTimeout (1 );
Cr.exe C ("ipconfig ");
}
}

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.