您的位置:首页 > 编程语言 > Java开发

java 调用外部命令

2012-10-30 17:08 351 查看
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.CyclicBarrier;

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.exec(__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().exec(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\\1h", "c:\\a_auto.txt",

// "c:\\b_auto.txt");

cr.setTimeout(1);

cr.exec("ipconfig");

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: