在网上常见的用java调用外部命令返回结果的方法是:
process =runtime.exec(cmd)
is = process.getinputstream();
isr=new inputstreamreader(is);
br =new bufferedreader(isr);
while( (line = br.readline()) != null )
{
out.println(line);
out.flush();
}
这种方法在遇到像cvs checkout modules这样不能马上返回结果的命令来说是无效的,不仅得不到返回结果,进程也会终止。其原因是,process在没有来得及gegtinputstream是,调用了bufferedreader.readline其返回结果是null,也就是说循环一开始就会停止。因此想要正常运行只能直接读取process.getinputstream(),如下:
import java.io.*;
/**
*
* @author tyrone
*
*/
public class cmdexecute
{
/**
* @param cmd
* @return
* @throws ioexception
*/
public synchronized string run(string[] cmd,string workdirectory) throws ioexception{
string line=null; string result="";
try {
processbuilder builder = new processbuilder(cmd);
//set working directory
if (workdirectory!=null)
builder.directory(new file(workdirectory));
builder.redirecterrorstream(true);
process process = builder.start();
inputstream in=process.getinputstream();
byte[] re=new byte[1024];
while (in.read(re)!= -1) {
system.out.println(new string(re));
result = result + new string(re);
}
in.close();
} catch (exception ex) {
ex.printstacktrace();
}
return result;
}
/**
* @param args=cvs log
*/ public static void main(string[] args){ string result=null;
cmdexecute cmdexe=new cmdexecute();
try {
result= cmdexe.run(args,"d://myproject//colimas//axis_c");
system.out.println(result);
}catch ( ioexception ex ){ ex.printstacktrace();
}
}
}
经过测试,本方法可以运行返回大量结果的应用程序。
闽公网安备 35060202000074号