java - 从文件位置在 Java 中运行 .exe 文件

标签 java windows batch-file exe bufferedreader

我必须从我的 Java 程序中打开一个 .exe 文件。所以我首先尝试了以下代码。

Process process = runtime.exec("c:\\program files\\test\\test.exe");

但是我遇到了一些错误。然后我发现 exe 必须从 c://program files/test/的位置启动,然后它才能打开而不会出现错误。所以我决定写一个 .bat 文件并执行,这样它就会 cd 到那个位置并执行 .exe 文件。

以下是我的代码:

BufferedWriter fileOut;

String itsFileLocation = "c:\\program files\\test\\"
    System.out.println(itsFileLocation);
    try {
     fileOut = new BufferedWriter(new FileWriter("C:\\test.bat"));
     fileOut.write("cd\\"+"\n");
     fileOut.write("cd "+ itsFileLocation +"\n");
     fileOut.write("test.exe"+"\n");
     fileOut.write("exit"+"\n");
     
     fileOut.close(); // Close the output stream after all output is done.
    } catch (IOException e1) {
     e1.printStackTrace();
    } // Create the Buffered Writer object to write to a file called filename.txt
    Runtime runtime = Runtime.getRuntime();
    try {
     Process process =runtime.exec("cmd /c start C:\\test.bat");
    } catch (IOException e) {
     e.printStackTrace();
    }

以上代码完美运行。但是,命令提示符也在我的 .exe(应用程序)后面打开。它仅在 .exe 文件退出后关闭。

我需要在我的应用程序统计信息时关闭我的命令提示符。

我的.bat文件被程序写入后会像下面这样

cd\
cd C:\Program Files\test\
test.exe
exit

最佳答案

您不需要控制台。您可以使用工作目录执行进程:

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

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

  • command是.exe所在的位置
  • envp 可以为空
  • dir,就是你的.exe所在的目录

关于您的代码,它应该是...

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

关于java - 从文件位置在 Java 中运行 .exe 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10685893/

相关文章:

java - 如何通过用户输入的表名和条件从oracle数据库中读取数据?

java - JDBC Statement.setFetchsize 是如何工作的

java - 从另一个类追加到 JTextArea

java - Java中如何从字符串中提取url?

c# - 使用 DownloadStringAsync 下载 HTML 源代码不会下载 WP8 上的整个源代码

c# - 找出用户属于哪个组

java - 如何将 java -jar 错误输出到文本/日志文件?

batch-file - 从具有许多子目录的主目录中批量提取特定文件类型

windows ->> 怎么称呼?

batch-file - 使用批处理删除文本文件的行