我必须从我的 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/