ITeye博客

java调用Dos命令

holoblog · 2008-11-14 18:49 · Markdown

比如我在工程文件夹下放了一个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会运行很长时间,那么在这段时间内就不能打印任何输出信息。

全代码如下:

  1. privatestaticbooleanCallSVM(Stringcmd)
  2. {
  3. Runtimerun=Runtime.getRuntime();
  4. Processchild=null;
  5. InputStreamis=null;
  6. try
  7. {
  8. Fileenv=newFile(System.getProperty("user.dir"));
  9. child=run.exec(cmd,null,env);
  10. Stringout=null;
  11. //nomalprocess
  12. is=child.getInputStream();
  13. FileWriterfw=newFileWriter(env.getAbsolutePath()+"//log.txt");
  14. BufferedReaderbr=newBufferedReader(newInputStreamReader(is));
  15. while((out=br.readLine())!=null)
  16. {
  17. fw.write(out+"/r/n");
  18. System.out.println(out);
  19. }
  20. while(true)
  21. {
  22. if(child.waitFor()==0)
  23. {
  24. break;
  25. }
  26. }
  27. fw.write("-----------------/r/n");
  28. fw.close();
  29. br.close();
  30. }
  31. catch(IOExceptionioe)
  32. {
  33. System.err.println("cmderror:"+cmd);
  34. System.err.println(ioe.getMessage());
  35. returnfalse;
  36. }catch(InterruptedExceptione){
  37. //TODOAuto-generatedcatchblock
  38. if(child!=null)
  39. child.destroy();
  40. e.printStackTrace();
  41. }
  42. returntrue;
  43. }

这里一定要输出放前,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()那里去了。

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。