说明

Windows应用,项目开发中,用到了调用其他exe的程序,因此做个整理,如下。

Windows下调用exe,权限设置:

cmd怎么运行java程序(JavaWindows环境下执行CMD命令)(1)

cmd怎么运行java程序(JavaWindows环境下执行CMD命令)(2)

案例代码

import java.io.BufferedReader; import java.io.InputStreamReader; /** * Java执行CMD */ public class RuntimeCMD { /** * @param cmd */ public static void exe(String cmd){ BufferedReader br = null; try { Process p = Runtime.getRuntime().exec(cmd); br = new BufferedReader(new InputStreamReader(p.getInputStream())); String line = null; while ((line = br.readLine()) != null) { System.out.println(line); } } catch (Exception e) { e.printStackTrace(); } finally { if (br != null) { try { br.close(); } catch (Exception e) { e.printStackTrace(); } } } } /** * @param cmd */ public static void exe(String[] cmds){ BufferedReader br = null; try { Process p = Runtime.getRuntime().exec(cmds); br = new BufferedReader(new InputStreamReader(p.getInputStream())); String line = null; while ((line = br.readLine()) != null) { System.out.println(line); } } catch (Exception e) { e.printStackTrace(); } finally { if (br != null) { try { br.close(); } catch (Exception e) { e.printStackTrace(); } } } } /** * @param args */ public static void main(String[] args) { exe("net user"); String[] cmds = new String[3]; cmds[0] = "cmd"; cmds[1] = "/c"; cmds[2] = "notepad"; exe(cmds); } }

测试,执行exe程序:

public class CloseOrderCMDTest { /** * @param args */ public static void main(String[] args) { String str = "D:\\MyProject\\trader-desktop-assistant\\CloseOrder.exe"; RuntimeCMD.exe(str); } }

,