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

查看:193
本文介绍了从文件位置运行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\\"+"\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文件退出后关闭..

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\test\
test.exe
exit


推荐答案

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

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

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

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

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

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


  • 命令是位置of .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天全站免登陆