首页 > 解决方案 > 如何使用 Java 运行 exe 文件

问题描述

这是我的代码:

import java.io.IOException;

public class testv1 {

    public static void main (String[] args) {
        System.out.println("ABC");
        try {
            Process proc = Runtime.getRuntime()
                        .exec("D:\\Program\\Pyinstaller\\Merge\\Test\\dist\\helloworld.exe"); 
        } catch (IOException e) { 
            e.printStackTrace(); 
        }

        System.out.println("Done");
    }
}

我想运行 helloworld.exe 但它不起作用。该程序正在打印

ABC
DONE

我也试过这个:

import java.io.File;
import java.io.IOException;
public class testv1 {
    public static void main (String[] args) {
        System.out.println("ABC");
        try
        {
            Runtime.getRuntime().exec("D:\\Program\\Pyinstaller\\Merge\\Test\\dist\\helloworld.exe", null, new File("D:\\Program\\Pyinstaller\\Merge\\Test\\dist\\"));
        }
        catch (IOException e) 
        { 
            e.printStackTrace(); 
        } 
        System.out.println("Done");
    }
}

但与前一个输出相同。

标签: java

解决方案


您可以使用工作目录执行进程:

exec(字符串命令,字符串 [] envp,文件目录)

在具有指定环境和工作目录的单独进程中执行指定的字符串命令。

command 是 .exe envp 的位置,可以是 null dir,是你的 .exe 的目录,就你的代码而言,它应该是......

Runtime.getRuntime().exec("c:\\program files\\test\\test.exe", null, new File("c:\\program files\\test\\"));

您可以使用 Runtime.exec(java.lang.String, java.lang.String[], java.io.File) 在其中设置工作目录。

否则,您可以按如下方式使用 ProcessBuilder:

ProcessBuilder pb = new ProcessBuilder("myCommand", "myArg1", "myArg2");
pb.directory(new File("myDir"));
Process p = pb.start();

从进程读取输出:

BufferedReader reader = 
                new BufferedReader(new InputStreamReader(process.getInputStream()));
StringBuilder builder = new StringBuilder();
String line = null;
while ( (line = reader.readLine()) != null) {
   builder.append(line);
   builder.append(System.getProperty("line.separator"));
}
String result = builder.toString();

推荐阅读