java调用Dos命令
比如我在工程文件夹下放了一个svm-train.exe的文件
这个exe文件调用后有输出信息。我很想知道这个exe调用过程中到底发生了什么事情。
在java中这样写
Runtime run = Runtime.getRuntime();
Process child = null;
InputStream is = null;
File env = new File(System.getProperty("user.dir"));
child = run.exec(cmd,null,env);
这个env是用于找到工程的当前目录,相当于进入Dos后先cd到目录,cmd就是你在dos窗口那里打的命令。
run.exec(cmd,null,env);这句就开始执行了。并创建一个Process给child
网上有很多代码有这句:
while(true)
{
if(child.waitFor() == 0)
{
break;
}
}
但是注意如果进入if(child.waitFor() == 0)
那这个程序就会卡死在这里,直到exe进程结束。这样如果你的exe会运行很长时间,那么在这段时间内就不能打印任何输出信息。
全代码如下:
- privatestaticbooleanCallSVM(Stringcmd)
- {
- Runtimerun=Runtime.getRuntime();
- Processchild=null;
- InputStreamis=null;
- try
- {
- Fileenv=newFile(System.getProperty("user.dir"));
- child=run.exec(cmd,null,env);
- Stringout=null;
- //nomalprocess
- is=child.getInputStream();
- FileWriterfw=newFileWriter(env.getAbsolutePath()+"//log.txt");
- BufferedReaderbr=newBufferedReader(newInputStreamReader(is));
- while((out=br.readLine())!=null)
- {
- fw.write(out+"/r/n");
- System.out.println(out);
- }
- while(true)
- {
- if(child.waitFor()==0)
- {
- break;
- }
- }
- fw.write("-----------------/r/n");
- fw.close();
- br.close();
- }
- catch(IOExceptionioe)
- {
- System.err.println("cmderror:"+cmd);
- System.err.println(ioe.getMessage());
- returnfalse;
- }catch(InterruptedExceptione){
- //TODOAuto-generatedcatchblock
- if(child!=null)
- child.destroy();
- e.printStackTrace();
- }
- returntrue;
- }
这里一定要输出放前,waitFor放后
while((out = br.readLine())!=null)
{
fw.write(out+"/r/n");
System.out.println(out);
}
while(true)
{
if(child.waitFor() == 0)
{
break;
}
}
另外程序在执行过程中while((out = br.readLine())!=null)这里也会卡住,所以不用担心,调用的dos程序还没有输出,就已经执行到waitFor()那里去了。