java执行可执行文件

文章目录

概要

java执行bat或shell脚本的方式主要有三种方式

1、 使用Runtime.exec

2、 使用ProcessBuilder

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

使用Runtime.exec

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

java 复制代码
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 提供了更强大和灵活的功能,并允许你更好地控制进程的执行。

java 复制代码
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 文件中添加以下依赖:

xml 复制代码
<dependency>  
    <groupId>org.apache.commons</groupId>  
    <artifactId>commons-exec</artifactId>  
    <version>1.3</version> <!-- 使用你需要的版本号 -->  
</dependency>
java 复制代码
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;
	}
}
相关推荐
南山十一少几秒前
Spring Security+JWT+Redis实现项目级前后端分离认证授权
java·spring·bootstrap
427724002 小时前
IDEA使用git不提示账号密码登录,而是输入token问题解决
java·git·intellij-idea
chengooooooo2 小时前
苍穹外卖day8 地址上传 用户下单 订单支付
java·服务器·数据库
李长渊哦2 小时前
常用的 JVM 参数:配置与优化指南
java·jvm
计算机小白一个2 小时前
蓝桥杯 Java B 组之设计 LRU 缓存
java·算法·蓝桥杯
南宫生5 小时前
力扣每日一题【算法学习day.132】
java·学习·算法·leetcode
计算机毕设定制辅导-无忧学长5 小时前
Maven 基础环境搭建与配置(一)
java·maven
风与沙的较量丶6 小时前
Java中的局部变量和成员变量在内存中的位置
java·开发语言
m0_748251726 小时前
SpringBoot3 升级介绍
java
极客先躯7 小时前
说说高级java每日一道面试题-2025年2月13日-数据库篇-请说说 MySQL 数据库的锁 ?
java·数据库·mysql·数据库的锁·模式分·粒度分·属性分