近期在项目开发过程中,采用osgi框架进行开发,由于开发过程中,每个模块(功能)都是采用独立的bundle进行部署,所以每次修改完一个bundle的java文件后,
都需要进行清理、打包、部署,非常麻烦,所以想让这些无意义的工作自动化处理,于是写了个自动化处理的小工具类,具体处理代码每个项目组可能都不一样,下面我
贴出主要代码部分:java操作cmd命令
//1、编译打包
String[] command =
{
"cmd",
};
Process p = null;
try {
p = Runtime.getRuntime().exec(command);
new Thread(new SyncPipe(p.getErrorStream(), System.err)).start();
new Thread(new SyncPipe(p.getInputStream(), System.out)).start();
PrintWriter stdin = new PrintWriter(p.getOutputStream());
/**以下可以输入自己想输入的cmd命令*/
stdin.println("d:"); //定位到D盘根目录
stdin.println("cd "+PROGRAM_ROOT_PATH); //cd到项目所在路径
stdin.println("mvn clean"); //清理
stdin.println("mvn package"); //打包
stdin.close();
} catch (Exception e) {
throw new RuntimeException("编译出现错误:"+e.getMessage());
}
/**
* <pre>
* 本类的代码来自http://stackoverflow.com/questions/4157303/how-to-execute-cmd-commands-via-java中
* 以为网友的回答
* </pre>
* @author le.zhou
* @version V1.0, 2014-7-28 上午11:04:45
*/
class SyncPipe implements Runnable
{
public SyncPipe(InputStream istrm, OutputStream ostrm) {
istrm_ = istrm;
ostrm_ = ostrm;
}
public void run() {
try{
final byte[] buffer = new byte[1024];
for (int length = 0; (length = istrm_.read(buffer)) != -1;){
ostrm_.write(buffer, 0, length);
}
}
catch (Exception e) {
throw new RuntimeException("处理命令出现错误:"+e.getMessage());
}
}
private final OutputStream ostrm_;
private final InputStream istrm_;
}