如何使用 Java 中执行 Windows 的 CMD 命令

  • 核心代码
  • 完整代码

  在 CMD 中执行 BAT 脚本对用户不友好,而且有安全隐患,因此笔者编写了一些可以在 Java 中执行 Windows 的 CMD 命令的 API。

核心代码

  • 执行单条命令
package org.wangpai.demo;import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.util.stream.Collectors;
import lombok.AccessLevel;
import lombok.Getter;
import lombok.experimental.Accessors;/*** @since 2021-12-21*/
@Accessors(chain = true)
public class WinCmd {private Charset cmdCharset;@Getter(AccessLevel.PROTECTED)private Process process;private String originalCommandMsg;private String output;private int exitValue;private WinCmd() {super();}public static WinCmd getInstance() {return new WinCmd();}/*** 如果调用本方法时,本方法会阻塞调用线程,直到命令执行结束** @since 2021-12-21*/public int getExitValue() throws Exception {if (this.process == null) {throw new Exception("需要先执行命令后才能获取退出码");}this.exitValue = process.waitFor();return this.exitValue;}public String getOutput() throws Exception {if (this.process == null) {throw new Exception("需要先执行命令后才能获取输出");}if (this.output != null) {return this.output;}var inputStream = process.getInputStream();// 获取操作系统(命令行)的字符集this.cmdCharset = Charset.forName((String) System.getProperties().get("sun.jnu.encoding"));// 将输出按行分成多个字符串。这原本不是想要的操作,但这没有办法var lines = new BufferedReader(new InputStreamReader(inputStream, this.cmdCharset)).lines();this.output = lines.collect(Collectors.joining(System.lineSeparator()));// 将每行字符串以换行符拼接,还原出原始信息return this.output;}public String getCommand() throws Exception {if (this.originalCommandMsg == null) {throw new Exception("还没有输入命令");}return this.originalCommandMsg;}public WinCmd execute(String command) throws Exception {return this.exec(command);}private WinCmd exec(String originalCommand) throws IOException {this.output = null;this.originalCommandMsg = originalCommand;this.process = Runtime.getRuntime().exec(this.originalCommandMsg);return this;}
}
  • 执行多条命令
package org.wangpai.demo;import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.util.stream.Collectors;
import java.util.stream.Stream;/*** @since 2021-12-21*/
public class WinBat {private int commandNum;private Charset cmdCharset;private String[] originalCommandMsg;private Process[] processArray;private String[] outputs;private int[] exitValues;private WinBat() {super();}public static WinBat getInstance() {return new WinBat();}public String getIntegrationOutput() throws Exception {if (this.processArray == null) {throw new Exception("需要先执行命令后才能获取输出");}if (this.outputs == null) {// 获取操作系统(命令行)的字符集this.cmdCharset = Charset.forName((String) System.getProperties().get("sun.jnu.encoding"));this.outputs = new String[this.commandNum];InputStream inputStream;for (int index = 0; index < this.commandNum; ++index) {inputStream = this.processArray[index].getInputStream();// 将输出按行分成多个字符串。这原本不是想要的操作,但这没有办法var linesOutput = new BufferedReader(new InputStreamReader(inputStream, this.cmdCharset)).lines();// 将每行字符串以换行符拼接,还原出原始信息this.outputs[index] = linesOutput.collect(Collectors.joining(System.lineSeparator()));}}var stream = Stream.of(this.outputs);// 多加一个空行作不同命令输出之间的分隔return stream.collect(Collectors.joining(System.lineSeparator() + System.lineSeparator()));}public String getIntegrationCommand() throws Exception {if (this.originalCommandMsg == null) {throw new Exception("还没有输入命令");}var stream = Stream.of(this.originalCommandMsg);return stream.collect(Collectors.joining(System.lineSeparator()));}public String[] getOriginalCommand() throws Exception {if (this.originalCommandMsg == null) {throw new Exception("还没有输入命令");}return this.originalCommandMsg;}/*** 如果调用本方法时,本方法会阻塞调用线程,直到命令执行结束** @since 2021-12-21*/public int[] getExitValues() throws Exception {if (this.processArray == null) {throw new Exception("需要先执行命令后才能获取退出码");}this.exitValues = new int[this.commandNum];for (int index = 0; index < this.commandNum; ++index) {this.exitValues[index] = this.processArray[index].waitFor();}return this.exitValues;}/*** 如果调用本方法时,本方法会阻塞调用线程,直到命令执行结束** @since 2021-12-21*/public int getLastExitValues() throws Exception {if (this.processArray == null) {throw new Exception("需要先执行命令后才能获取退出码");}var exitValues = this.getExitValues();return exitValues[this.commandNum - 1];}private WinBat exec(String[] originalCommand) throws Exception {this.outputs = null;this.originalCommandMsg = originalCommand;this.commandNum = originalCommand.length;this.processArray = new Process[this.commandNum];for (int index = 0; index < this.commandNum; ++index) {this.processArray[index] = WinCmd.getInstance().execute(this.originalCommandMsg[index]).getProcess();}return this;}public WinBat execute(String[] command) throws Exception {return this.exec(command);}
}

完整代码

  已上传至 GitCode 中,可免费下载:https://gitcode.net/wangpaiblog/20220110-win_cmd

如何使用 Java 中执行 Windows 的 CMD 命令相关推荐

  1. java执行windows下cmd命令的方法

    本文实例讲述了java执行windows下cmd命令的方法.分享给大家供大家参考. 具体实现代码如下: 复制代码 代码如下: //获取运行时 Runtime rt = Runtime.getRunti ...

  2. 如何在Python中调用Windows的cmd命令?

    简 介: 利用os,commands,subprocess模块可以在python中调用windows中的命令.从使用方便性上来看,利用os.popen可以执行windows的程序并可以获得返回内容. ...

  3. Java中执行Linux文件删除命令 rm -rf

    public static void deleteFile(String destDirPath) {String property = System.getProperty("os.nam ...

  4. java调用多条cmd命令_Java中调用多条cmd命令

    使用Java执行cmd代码很简单: try{ Runtime.getRuntime().exec("cd /d E:"); }catch (Exception e) { e.pri ...

  5. java触发器如何创建表_在java 中执行触发器代码、创表语句

    由于程序的需要,在SQLServer 中创建触发器及建表,碰到了在java 代码中执行创建触发器及表. /**建立中间表*/ public static final String createMidd ...

  6. java解析shell命令_Android中执行java命令的方法及java代码执行并解析shell命令

    这篇文章给大家介绍Android中执行java命令的方法及java代码执行并解析shell命令,需要的朋友一起学习 android中执行java命令的方法大家都晓得吗,下面一段内容给大家带来了具体解析 ...

  7. linux java 终端命令大全_在java中执行linux终端命令?

    我正在尝试从java执行SOX命令,但不幸的是它每次都返回一个错误.其他每个SOX命令都运行得很好!! 这是代码: class Simple { public static void main(Str ...

  8. windows下cmd命令行显示UTF8字符设置(CHCP命令)

    点我进入原文 windows下cmd命令行显示UTF8字符设置(CHCP命令) 在中文Windows系统中,如果一个文本文件是UTF-8编码的,那么在CMD.exe命令行窗口(所谓的DOS窗口)中不能 ...

  9. C++程序如何执行cmd命令;如何对cmd命令执行计时;如何一行执行多条cmd命令;

    今天在做实验,测试各种压缩算法的性能时,遇到zstd算法在执行时不会自动输出压缩时间的问题,所以就想法子在cpp程序中给它执行再计时: C++程序如何执行cmd命令 直接上答案:system(要执行的 ...

最新文章

  1. Zabbix配置模板监控指定服务器主机
  2. 【输入一个年份,判断是否为闰年(leap year)】
  3. 为什么Docker,Vagrant和Ansible等工具比以往更热门
  4. 喜报!木兰宽松许可证通过OSI认证,成为首个中英双语国际开源许可证!
  5. java 怎么入门_学习java怎么入门
  6. mysql软件可行性分析报告_网上商城系统可行性分析报告.doc
  7. 最全支付系统设计包含:账户,对账,风控...
  8. JS获取当前时间的日周月年的开始结束时间
  9. 亮相SIGGRAPH 太极拳三维教学App制作揭秘
  10. hive分隔符_hive分隔符总结
  11. 微信小程序:javascript调用另一个js文件的函数
  12. 做一个商业网站需要准备什么,需要多少钱?
  13. QQ引流脚本,QQ扩列引流脚本实操演示
  14. python 绘图-时间显示
  15. 爸妈,对不起,那不是我本意
  16. 登录时设置验证码的作用及实现
  17. Java编写一个原始的聊天室(线程、服务器-客户端)
  18. 大航海时代 收夺全攻略
  19. malloc实现原理探究
  20. MySQL 备份的操作步骤

热门文章

  1. 基于python、虹软实现人脸检测,人脸识别
  2. 浏览器渲染流水线解析
  3. 随笔-546 评论-829 文章-21 2015年第15本:天才在左,疯子在右
  4. linux 免密码登录
  5. Web服务(Apache、Nginx、Tomcat、Jetty)与应用(LAMP、CMS-WordPressGhost、Jenkins、Gitlab)
  6. Cisco 2900 series添加VWIC2-1MFT-G703板卡
  7. 《Nginx文件类型错误解析漏洞--攻击演练》 (转)
  8. AspNet.WebAPI.OData.ODataPQ实现WebAPI的分页查询服务-(个人拙笔)
  9. Ticker View
  10. request Form request QueryString