java中调用exe程序和问题处理

发布时间 2024-01-11 12:02:37作者: JackGIS
常规方法如下:
public class RunExe {
    public static void main(String[] args) {
        try {
            // exe文件的完整路径
            String filePath = "C:\\path\\to\\your\\program.exe";

            // 运行exe程序
            Process p = Runtime.getRuntime().exec(filePath);

            // 你也可以读取程序的输出(如果需要)
            BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));

            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }

            // 等待程序执行完毕并输出退出值
            int exitCode = p.waitFor();
            System.out.println("Exited with code: " + exitCode);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

当用cmd执行exe,并且需要切换到exe目录下的话,需要改造filePath:

String command = "cmd /c d: && cd D:/PMF && ME-2.exe ";

先切换到d盘,然后切换到d:/PMF目录,然后执行exe。

问题1:idea停了之后,exe才运行。并且process.waitFor()这个代码执行后,程序一直等待。

Process process = Runtime.getRuntime().exec("你的命令");

// 处理标准输出
new Thread(() -> {
    try (BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()))) {
        String line;
        while ((line = reader.readLine()) != null) {
            System.out.println(line);
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}).start();

// 处理错误输出
new Thread(() -> {
    try (BufferedReader reader = new BufferedReader(new InputStreamReader(process.getErrorStream()))) {
        String line;
        while ((line = reader.readLine()) != null) {
            System.err.println(line);
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}).start();

// 等待进程结束
int exitValue = process.waitFor();
if (exitValue == 0) {
    // 执行成功的处理
} else {
    // 执行失败的处理
}

在这个示例中,创建了两个线程,分别用于读取外部进程的标准输出和错误输出。这可以防止因为未读取输出而导致的进程挂起。同时,这样的处理也使得Java程序能够即时地获取和响应外部进程的输出。

问题2:程序部署到tomcat后,调用exe的时候报错:java.io.FileNotFoundException

这个一般是权限不够导致的,处理方法如下:

1、修改exe文件目录的权限

 

2、修改tomcat登录身份

3、修改tomcat目录权限