比如我在工程檔案夾下放了一個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會運行很長時間,那麼在這段時間內就不能列印任何輸出資訊。
全代碼如下:
- private static boolean CallSVM(String cmd)
- {
- Runtime run = Runtime.getRuntime();
- Process child = null;
- InputStream is = null;
-
- try
- {
- File env = new File(System.getProperty("user.dir"));
-
- child = run.exec(cmd,null,env);
-
- String out = null;
-
-
- // nomal process
- is = child.getInputStream();
- FileWriter fw = new FileWriter(env.getAbsolutePath()+"//log.txt");
- BufferedReader br = new BufferedReader(new InputStreamReader(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(IOException ioe)
- {
- System.err.println("cmd error:"+cmd);
- System.err.println(ioe.getMessage());
- return false;
- } catch (InterruptedException e) {
- // TODO Auto-generated catch block
- if(child != null)
- child.destroy();
- e.printStackTrace();
- }
- return true;
- }
這裡一定要輸出放前,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()那裡去了。