---
title: "java调用Dos命令"
author: "holoblog"
date: "2008-11-14T18:49:00Z"
tags: []
slug: "java-dos"
draft: false
lastmod: "2011-11-11T11:21:48Z"
id: 1251916
url: "https://holoblog.iteye.com/blog/1251916"
---

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

全代码如下：

01. privatestaticbooleanCallSVM(Stringcmd)
02. {
03. Runtimerun=Runtime.getRuntime();
04. Processchild=null;
05. InputStreamis=null;
06. try
07. {
08. Fileenv=newFile(System.getProperty("user.dir"));
09. 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()那里去了。