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

标准java调用外部命令的写法

2012-09-07 00:22 288 查看
闲着没事写了个java调用外部命令的例子,供以后参考用,不得不说代码行比用perl多了好几个数量级

perl版本
my @result = qx(ls);
# runs command and returns its STDOUT

my @results = `ls`;
# dito, alternative syntax

system "ls";
# runs command and returns its exit status

print `ls`;
#The same, but with back quotes

exec "ls";
# replace current process with another


java版本
package com.thejtechs.systemcmd;

import java.io.IOException;
import java.util.Timer;

/**
* 执行外部命令
* @author thejtechs.com
*
*/
public class SystemCmdExecutor {

//这里可以构造一个Command对象作为参数,以提供更好的扩展
public boolean execute(String cmd, long timeout, int expectReturnCode){
boolean result = true;
Timer timer = new Timer();
try {
CommandTokenizer tokenizer = new CommandTokenizer(cmd);
Process p = Runtime.getRuntime().exec(tokenizer.tokenize());
//为了防止JVM挂起,开启辅助线程接收和打印输出
CommandStreamPrinter outputPrinter = new CommandStreamPrinter(p.getInputStream(), "Standard output");
CommandStreamPrinter errorPrinter = new CommandStreamPrinter(p.getErrorStream(), "Error output");
new Thread(outputPrinter).start();
new Thread(errorPrinter).start();
CommandTimeoutTask timeoutTask = new CommandTimeoutTask(p);
timer.schedule(timeoutTask, timeout * 1000);  // Convert seconds to millis
int returnCode = p.waitFor();
if(expectReturnCode != returnCode){
System.out.print("Command[" + cmd + "] execute failed, return code is : " + returnCode);
result = false;
}
//正常执行完
timeoutTask.cancel();
} catch (IOException e) {
//TODO log this exception
e.printStackTrace();
result = false;
} catch (InterruptedException e) {
e.printStackTrace();
//TODO log this exception
result = false;
}
timer.cancel();
return result;
}

public static void main(String args[]){
new SystemCmdExecutor().execute("cmd.exe /C dir C:\\Dev", 2, 0);
}

}

package com.thejtechs.systemcmd;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.StreamTokenizer;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.List;

/**
* 分割命令字符串
* @author thejtechs.com
*
*/
public class CommandTokenizer {

private String cmd;

public CommandTokenizer(String cmd){
this.cmd = cmd;
}

public String[] tokenize(){
List cmdStrings = new ArrayList();
try {
StreamTokenizer sTokenizer = new StreamTokenizer(new BufferedReader(new StringReader( cmd )));
sTokenizer.ordinaryChars('!', '~'); //'!'和'~'之间的字符时普通字符,不含任何特殊含义
sTokenizer.wordChars('!', '~'); //'!'和'~'之间的所有字符都被当作为单词的要素。一个单词是由一个单词要素后面跟着0个或者更多个单词要素或者数字要素
sTokenizer.ordinaryChar('\'');
sTokenizer.ordinaryChar('\"');
sTokenizer.quoteChar('\''); //在单引号之间的内容当做一个字符串解析
sTokenizer.quoteChar('\"');
while (sTokenizer.nextToken() != StreamTokenizer.TT_EOF) {
cmdStrings.add( sTokenizer.sval );
}
} catch (IOException e) {
System.out.println(e.toString());
}
return cmdStrings.toArray(new String[1]);
}

}

package com.thejtechs.systemcmd;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

/**
* 打印命令执行的标准输出流和错误流的线程
*
* @author thejtechs.com
*
*/
public class CommandStreamPrinter implements Runnable {

private InputStream is;
private String type;
private String outputAsString;
private int maxLength = 1024 * 1000; // 1MB

public CommandStreamPrinter(InputStream is, String type) {
this.is = is;
this.type = type;
}

@Override
public void run() {
try {
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line = null;
StringBuffer sb = new StringBuffer();
while ((line = br.readLine()) != null) {
System.out.println(type + " >>> " + line);
if (sb.length() < maxLength) {
sb.append(line);
}
}
outputAsString = sb.toString();
} catch (IOException e) {
e.printStackTrace();
}
}

public String getOutputAsString() {
return outputAsString;
}

}

package com.thejtechs.systemcmd;

import java.util.TimerTask;

/**
* 当命令执行超时时,负责销毁任务
*
* @author thejtechs.com
*
*/
public class CommandTimeoutTask extends TimerTask {

private Process proc;

public CommandTimeoutTask(Process proc) {
this.proc = proc;
}

@Override
public void run() {
System.out.println("Process [" + proc.toString() + "] has timed out.");
proc.destroy();

}

}

参考:http://www.thejtechs.com/blogDetail/75/java-execute-system-command
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息