java调用Dos命令

来源:互联网 发布:哪些平台可以做淘宝客 编辑:程序博客网 时间:2024/05/27 12:21

 比如我在工程文件夹下放了一个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.     private static boolean CallSVM(String cmd)
  2.     {
  3.         Runtime run = Runtime.getRuntime();     
  4.         Process child = null;
  5.         InputStream is = null;
  6.         
  7.         try
  8.         {
  9.             File env = new File(System.getProperty("user.dir"));
  10.             
  11.             child = run.exec(cmd,null,env);
  12.             
  13.             String out = null;
  14.         
  15.             
  16.             // nomal process
  17.             is = child.getInputStream();
  18.             FileWriter fw = new FileWriter(env.getAbsolutePath()+"//log.txt");            
  19.             BufferedReader br = new BufferedReader(new InputStreamReader(is));
  20.             
  21.             while((out = br.readLine())!=null)
  22.             {
  23.                 fw.write(out+"/r/n");
  24.                 System.out.println(out);
  25.             }
  26.             while(true)
  27.             {
  28.                 if(child.waitFor() == 0)
  29.                 {
  30.                     break;
  31.                 }
  32.             }
  33.             fw.write("-----------------/r/n");
  34.             
  35.             fw.close();
  36.             br.close();
  37.             
  38.         }
  39.         catch(IOException ioe)
  40.         {
  41.             System.err.println("cmd error:"+cmd);
  42.             System.err.println(ioe.getMessage());
  43.             return false;
  44.         } catch (InterruptedException e) {
  45.             // TODO Auto-generated catch block
  46.             if(child != null)
  47.                 child.destroy();
  48.             e.printStackTrace();
  49.         }
  50.         return true;
  51.     }

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

原创粉丝点击