java执行可执行文件

news/2025/3/27 12:24:37/

文章目录

    • 概要
    • 使用Runtime.exec
    • 使用ProcessBuilder
    • 使用第三方工具包commons-exec.jar

概要

java执行bat或shell脚本的方式主要有三种方式
1、 使用Runtime.exec
2、 使用ProcessBuilder
3、 使用第三方的工具包commons-exec.jar

使用Runtime.exec

在 Java 中,使用 Runtime.exec() 方法执行外部可执行文件是一个常见的做法。但是,这种方法有一些限制和潜在的问题,比如它不太容易处理进程的输入/输出流。


import java.io.IOException;import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/*** 类名称: ExeRunUtil.* 类描述: 执行cmd命令*/
public class ExeRunUtil{private static Log log = LogFactory.getLog(ExeRunUtil.class);/** * 执行cmd命令* @return 执行结果*/  public static boolean exec(String[] command) {  Process proc;  try { proc = Runtime.getRuntime().exec(command);   new StreamReader(proc,proc.getInputStream(),"Output" ).start();new StreamReader(proc,proc.getErrorStream(),"Error").start();} catch (IOException ex) {  log.error("IOException while trying to execute " + command,ex);return false;  }  int exitStatus=1;  try {  exitStatus = proc.waitFor();  //等待操作完成 } catch (java.lang.InterruptedException ex) {   log.error("InterruptedException command: " + exitStatus,ex);}   if (exitStatus != 0) {   log.error("Error executing command: " + exitStatus);}  return (exitStatus == 0);  }  
}import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/*** 获取exe执行信息* @author shandongwill**/
public class StreamReader extends Thread{private final Log logger = LogFactory.getLog(getClass());private InputStream is;  private String type;  private Process proc;public StreamReader(Process proc,InputStream is, String type) {  this.is = is;  this.type = type;  this.proc=proc;}  public void run() {  try {  InputStreamReader isr = new InputStreamReader(is);  BufferedReader br = new BufferedReader(isr);  String line = null;  while ((line = br.readLine()) != null) {  if (type.equals("Error")) {  logger.error("Error:" + line);  proc.destroyForcibly();} else {  logger.debug("Debug:" + line);  }  }  } catch (IOException ioe) {  logger.error(ioe);  }  } 
}

使用ProcessBuilder

相比于 Runtime.exec(),ProcessBuilder 提供了更强大和灵活的功能,并允许你更好地控制进程的执行。

ProcessBuilder processBuilder = new ProcessBuilder("cmd.exe", "/c", "test.bat");
processBuilder.redirectErrorStream(true);
Process process = processBuilder.start();
int exitCode = process.waitFor();
BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {System.out.println(line);
}
System.out.println("Exit code: " + exitCode);

使用第三方工具包commons-exec.jar

commons-exec.jar 是 Apache Commons Exec 库的一部分,它提供了一个更强大和灵活的 API 来执行外部进程。与 Java 的标准 Runtime.exec() 和 ProcessBuilder 类相比,Apache Commons Exec 提供了更多的功能和更好的错误处理。
使用 Apache Commons Exec,你可以更容易地管理进程执行,包括设置进程的工作目录、环境变量、输入/输出流重定向、超时处理等。此外,它还提供了更好的错误消息和异常处理,帮助开发者更容易地诊断问题。
要使用 commons-exec.jar,你需要将其添加到你的项目依赖中。如果你使用 Maven,你可以在 pom.xml 文件中添加以下依赖:

<dependency>  <groupId>org.apache.commons</groupId>  <artifactId>commons-exec</artifactId>  <version>1.3</version> <!-- 使用你需要的版本号 -->  
</dependency>

import java.io.ByteArrayOutputStream;
import java.io.IOException;import org.apache.commons.exec.CommandLine;
import org.apache.commons.exec.DefaultExecutor;
import org.apache.commons.exec.ExecuteException;
import org.apache.commons.exec.ExecuteWatchdog;
import org.apache.commons.exec.PumpStreamHandler;/*** CMD工具类* * @author Administrator**/
public class CmdUtils {/*** 执行命令* * @param command:命令* @return String[]数组,String[0]:返回的正常信息;String[1]:返回的警告或错误信息* @throws ExecuteException* @throws IOException*/public static String[] handle(String command) throws ExecuteException, IOException {// 接收正常结果流ByteArrayOutputStream outputStream = new ByteArrayOutputStream();// 接收异常结果流ByteArrayOutputStream errorStream = new ByteArrayOutputStream();CommandLine commandline = CommandLine.parse(command);DefaultExecutor exec = new DefaultExecutor();exec.setExitValues(null);// 设置10分钟超时ExecuteWatchdog watchdog = new ExecuteWatchdog(600 * 1000);exec.setWatchdog(watchdog);PumpStreamHandler streamHandler = new PumpStreamHandler(outputStream, errorStream);exec.setStreamHandler(streamHandler);exec.execute(commandline);// 不同操作系统注意编码,否则结果乱码String out = outputStream.toString("UTF-8");String error = errorStream.toString("UTF-8");// 返回信息String[] result = new String[2];result[0] = out;result[1] = error;return result;}
}

http://www.ppmy.cn/news/1343759.html

相关文章

指针进阶(3)(超详细)

给大家分享一句我很喜欢我话&#xff1a; 知不足而奋进&#xff0c;望远山而前行&#xff01;&#xff01;&#xff01; 铁铁们&#xff0c;成功的路上必然是孤独且艰难的&#xff0c;但是我们不可以放弃&#xff0c;远山就在前方&#xff0c;但我们能力仍然不足&#xff0c;所…

麻雀搜索算法|Sparrow Search Algorithm(SSA)

在麻雀群体智慧、觅食和反捕食行为的启发下&#xff0c;提出了一种新的群体优化方法&#xff0c;即麻雀搜索算法&#xff08;SSA&#xff09;。 1、简介 在麻雀搜索算法中包含三种类型的麻雀个体&#xff0c;即发现者、跟随者和侦察者&#xff0c;三种类型对应三种行为。发现…

【LeetCode: 292. Nim 游戏+ 博弈问题】

&#x1f680; 算法题 &#x1f680; &#x1f332; 算法刷题专栏 | 面试必备算法 | 面试高频算法 &#x1f340; &#x1f332; 越难的东西,越要努力坚持&#xff0c;因为它具有很高的价值&#xff0c;算法就是这样✨ &#x1f332; 作者简介&#xff1a;硕风和炜&#xff0c;…

教你一招如何半小时把C语言的 scanf printf sscanf sprintf fscanf fprintf wscanf wprintf 玩出花来

本篇会加入个人的所谓‘鱼式疯言’ ❤️❤️❤️鱼式疯言:❤️❤️❤️此疯言非彼疯言 而是理解过并总结出来通俗易懂的大白话, 我会尽可能的在每个概念后插入鱼式疯言,帮助大家理解的. &#x1f92d;&#x1f92d;&#x1f92d;可能说的不是那么严谨.但小编初心是能让更多人能…

闲聊电脑(4)硬盘分区

夜深人静&#xff0c;万籁俱寂&#xff0c;老郭趴在电脑桌上打盹&#xff0c;桌子上的小黄鸭和桌子旁的冰箱又开始窃窃私语…… 小黄鸭&#xff1a;冰箱大哥&#xff0c;上次你说的那个“分区”和“格式化”是什么意思&#xff1f; 冰箱&#xff1a;分区么&#xff0c;就是分…

【计算机网络】物理层概述|通信基础|奈氏准则|香农定理|信道复用技术

目录 一、思维导图 二、 物理层概述 1.物理层概述 2.四大特性&#xff08;巧记"械气功程") 三、通信基础 1.数据通信基础 2.趁热打铁☞习题训练 3.信号の变身&#xff1a;编码与调制 4.极限数据传输率 5.趁热打铁☞习题训练 6.信道复用技术 推荐 前些天发…

Fink CDC数据同步(六)数据入湖Hudi

数据入湖Hudi Apache Hudi(简称&#xff1a;Hudi)使得您能在hadoop兼容的存储之上存储大量数据&#xff0c;同时它还提供两种原语&#xff0c;使得除了经典的批处理之外&#xff0c;还可以在数据湖上进行流处理。这两种原语分别是&#xff1a; Update/Delete记录&#xff1a;H…

ElementUI Form:Switch 开关

ElementUI安装与使用指南 Switch 开关 点击下载learnelementuispringboot项目源码 效果图 el-switch.vue &#xff08;Switch 开关&#xff09;页面效果图 项目里el-switch.vue代码 <script> export default {name: el_switch,data() {return {value: true,value1: …