Windows系统中Java调用cmd命令及执行exe程序的方法
Java调用cmd命令,并输出显示信息:
packagecom.anxin.cmd.test;
importjava.io.BufferedReader;
importjava.io.InputStreamReader;
publicclassCommand{
publicstaticvoidmain(String[]args){
try{
Runtimert=Runtime.getRuntime();
Processpr=rt.exec("cmd/cdir");//cmd/ccalc
//Processpr=rt.exec("D:\\xunlei\\project.aspx");
BufferedReaderinput=newBufferedReader(newInputStreamReader(pr.getInputStream(),"GBK"));
Stringline=null;
while((line=input.readLine())!=null){
System.out.println(line);
}
intexitVal=pr.waitFor();
System.out.println("Exitedwitherrorcode"+exitVal);
}catch(Exceptione){
System.out.println(e.toString());
e.printStackTrace();
}
}
}
Java启动本机应用程序EXE的三种方式:
第一种方式:利用cmd方式
/**
*执行cmd命令
*
*@paramcommand
*@throwsIOException
*/
publicstaticStringexecuteCmd(Stringcommand)throwsIOException{
log.info("Executecommand:"+command);
Runtimeruntime=Runtime.getRuntime();
Processprocess=runtime.exec("cmd/c"+command);
BufferedReaderbr=newBufferedReader(newInputStreamReader(process.getInputStream(),"UTF-8"));
Stringline=null;
StringBuilderbuild=newStringBuilder();
while((line=br.readLine())!=null){
log.info(line);
build.append(line);
}
returnbuild.toString();
}
executeCmd(start"AXAdWebBrowser""D:\AXAdsBrowser\AXAdWebBrowser.exe");
第二种方式:利用ProcessBuilder调用cmd方式
/**
*启动应用程序
*
*@paramprogramName
*@return
*@throwsIOException
*/
publicstaticvoidstartProgram(StringprogramPath)throwsIOException{
log.info("启动应用程序:"+programPath);
if(StringUtils.isNotBlank(programPath)){
try{
StringprogramName=programPath.substring(programPath.lastIndexOf("/")+1,programPath.lastIndexOf("."));
List<String>list=newArrayList<String>();
list.add("cmd.exe");
list.add("/c");
list.add("start");
list.add("\""+programName+"\"");
list.add("\""+programPath+"\"");
ProcessBuilderpBuilder=newProcessBuilder(list);
pBuilder.start();
}catch(Exceptione){
e.printStackTrace();
log.error("应用程序:"+programPath+"不存在!");
}
}
}
第三种方式:使用Desktop启动应用程序
/**
*启动应用程序
*
*@paramprogramName
*@return
*@throwsIOException
*/
publicstaticvoidstartProgram(StringprogramPath)throwsIOException{
log.info("启动应用程序:"+programPath);
if(StringUtils.isNotBlank(programPath)){
try{
Desktop.getDesktop().open(newFile(programPath));
}catch(Exceptione){
e.printStackTrace();
log.error("应用程序:"+programPath+"不存在!");
}
}
}