欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Windows系统中Java调用cmd命令及执行exe程序的方法

程序员文章站 2024-03-09 16:38:47
java调用cmd命令,并输出显示信息: package com.anxin.cmd.test; import java.io.bufferedre...

java调用cmd命令,并输出显示信息:

package com.anxin.cmd.test; 
 
import java.io.bufferedreader; 
import java.io.inputstreamreader; 

public class command { 
 
 public static void main(string[] args) { 
  try { 
   runtime rt = runtime.getruntime(); 
   process pr = rt.exec("cmd /c dir"); // cmd /c calc 
   // process pr = rt.exec("d:\\xunlei\\project.aspx"); 
 
   bufferedreader input = new bufferedreader(new inputstreamreader(pr.getinputstream(), "gbk")); 
 
   string line = null; 
 
   while ((line = input.readline()) != null) { 
    system.out.println(line); 
   } 
 
   int exitval = pr.waitfor(); 
   system.out.println("exited with error code " + exitval); 
 
  } catch (exception e) { 
   system.out.println(e.tostring()); 
   e.printstacktrace(); 
  } 
 } 
} 

java启动本机应用程序exe的三种方式:

第一种方式:利用cmd方式 

/** 
 * 执行cmd命令 
 * 
 * @param command 
 * @throws ioexception 
 */ 
public static string executecmd(string command) throws ioexception { 
 log.info("execute command : " + command); 
 runtime runtime = runtime.getruntime(); 
 process process = runtime.exec("cmd /c " + command); 
 bufferedreader br = new bufferedreader(new inputstreamreader(process.getinputstream(), "utf-8")); 
 string line = null; 
 stringbuilder build = new stringbuilder(); 
 while ((line = br.readline()) != null) { 
  log.info(line); 
  build.append(line); 
 } 
 return build.tostring(); 
} 
 
executecmd(start "axadwebbrowser" "d:\axadsbrowser\axadwebbrowser.exe"); 

第二种方式:利用processbuilder调用cmd方式

/** 
 * 启动应用程序 
 * 
 * @param programname 
 * @return 
 * @throws ioexception 
 */ 
public static void startprogram(string programpath) throws ioexception { 
 log.info("启动应用程序:" + programpath); 
 if (stringutils.isnotblank(programpath)) { 
  try { 
   string programname = programpath.substring(programpath.lastindexof("/") + 1, programpath.lastindexof(".")); 
   list<string> list = new arraylist<string>(); 
   list.add("cmd.exe"); 
   list.add("/c"); 
   list.add("start"); 
   list.add("\"" + programname + "\""); 
   list.add("\"" + programpath + "\""); 
   processbuilder pbuilder = new processbuilder(list); 
   pbuilder.start(); 
  } catch (exception e) { 
   e.printstacktrace(); 
   log.error("应用程序:" + programpath + "不存在!"); 
  } 
 } 
} 

第三种方式:使用desktop启动应用程序 

/** 
 * 启动应用程序 
 * 
 * @param programname 
 * @return 
 * @throws ioexception 
 */ 
public static void startprogram(string programpath) throws ioexception { 
 log.info("启动应用程序:" + programpath); 
 if (stringutils.isnotblank(programpath)) { 
  try { 
   desktop.getdesktop().open(new file(programpath)); 
  } catch (exception e) { 
   e.printstacktrace(); 
   log.error("应用程序:" + programpath + "不存在!"); 
  } 
 } 
}