从文件位置运行 Java 中的 .exe 文件 [英] Run .exe file in Java from file location

查看:38
本文介绍了从文件位置运行 Java 中的 .exe 文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have to open a .exe file from my Java program. So I tried following code First.

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

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

But I was getting some error. Then I found out that the exe has to be launched from that location that is c://program files/test/ only then it will open with out errors. So I decided to write a .bat file and execute so that it will cd to that location and execute the .exe file.

以下是我的代码:

BufferedWriter fileOut;

String itsFileLocation = "c:\program files\test\"
    System.out.println(itsFileLocation);
    try {
     fileOut = new BufferedWriter(new FileWriter("C:\test.bat"));
     fileOut.write("cd\"+"
");
     fileOut.write("cd "+ itsFileLocation +"
");
     fileOut.write("test.exe"+"
");
     fileOut.write("exit"+"
");
     
     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 文件退出后关闭..

The above code works perfectly. However, the command prompt is also opened at the back of my .exe (Application). It closes only after the .exe file exits..

当我的应用程序统计数据时,我需要关闭我的命令提示符.

I need to clse my command prompt when my application stats.

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

My .bat file will be like following after it is written by the program.

cd
cd C:Program Files	est
test.exe
exit

推荐答案

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

You don't need a console. You can execute a process using a working directory:

exec(String command, String[] envp, File dir)

exec(String command, String[] envp, File dir)

在单独的进程中执行指定的字符串命令使用指定的环境和工作目录.

Executes the specified string command in a separate process with the specified environment and working directory.

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

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

With respect to your code it should be...

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

这篇关于从文件位置运行 Java 中的 .exe 文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆