2009年4月22日星期三

Java 调用 exe与cmd 小结

有时候,需要在Java中调用现成的.exe文件或是cmd进行操作,下面结合自己的项目实例,做以小结。


现在我们的目标是:用Java调用cmd,执行C:/libsvm/windows/svm-train.exe,svm-train.exe参数为: [options] training_set_file [model_file]
具体是 -c 32 -g 0.0078125 trainset trainset.model
可以将doc窗口的输出显示到JAVA IDE的控制台上。

我们需要用到java.lang.Runtime类
主要成员函数:
getRuntime() 返回与当前 Java 应用程序相关的运行时对象。
Runtime r=Runtime.getRuntime();

exec(String command, String[] envp, File dir) 在有指定环境和工作目录的独立进程中执行指定的字符串命令。 。command为.exe及其参数,envp null即可,dir=new File(FilePath)

java.lang.Process类
主要成员函数:
waitFor() 导致当前线程等待,如果必要,一直要等到由该 Process 对象表示的进程已经终止。
注:Process p = Runtime.getRuntime().exec(arg)

实现代码如下:

import java.io.*;
import java.lang.*;

public class RunExe {

public static void main(String[] arg)
{
Runtime r = Runtime.getRuntime();


try
{
String[] cmd = new String[5];

cmd[0] = "cmd "; //命令行
cmd[1] = "/c "; //运行后关闭,
cmd[2] = "start "; //启动另一个窗口来运行指定的程序或命令(cmd 命令集里的)
cmd[3] = "C:\\libsvm\\windows"; //要运行的.exe程序的目录

cmd[4] = "svm-train -c 32 -g 0.0078125 -v 5 trainset ";//exe程序及其需要的参数
String Naiveexe = "calc.exe";//windows自带计算器
String line;
String space=" ";
//Process p = Runtime.getRuntime().exec("cmd /c svm-train.exe -c 32 -g 0.0078125 -v 5 trainset",null,new File("C:\\libsvm\\windows")); 此时输出到控制台
//Process p = Runtime.getRuntime().exec("cmd /c start svm-train.exe -c 32 -g 0.0078125 -v 5 trainset",null,new File("C:\\libsvm\\windows"));此时弹出dos窗口运行


Process p = Runtime.getRuntime().exec((cmd[0]+cmd[1]+cmd[4]),null,new File(cmd[3]));
//Process p = Runtime.getRuntime().exec("calc.exe"); //直接运行计算器



BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
while ( (line=br.readLine()) != null)
System.out.println(line);

//p.waitFor();
}


catch(Exception e)
{System.out.println("Error!");

}

OK,enjoy!

没有评论: