首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >从文件位置运行Java中的.exe文件

从文件位置运行Java中的.exe文件
EN

Stack Overflow用户
提问于 2012-05-21 21:10:22
回答 5查看 107K关注 0票数 20

我必须从我的Java程序打开一个.exe文件。所以我先试着跟着代码走。

代码语言:javascript
复制
Process process = runtime.exec("c:\\program files\\test\\test.exe");

但是我得到了一些错误。然后我发现exe必须从c://program files/test/这个位置启动,然后它才会打开,没有错误。因此,我决定编写一个.bat文件并执行,这样它就可以cd到该位置并执行.exe文件。

以下是我的代码:

代码语言:javascript
复制
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文件在被程序写入后将如下所示。

代码语言:javascript
复制
cd\
cd C:\Program Files\test\
test.exe
exit
EN

回答 5

Stack Overflow用户

发布于 2012-05-21 21:16:29

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

或者,您可以使用ProcessBuilder,如下所示:

代码语言:javascript
复制
ProcessBuilder pb = new ProcessBuilder("myCommand", "myArg1", "myArg2");
pb.directory(new File("myDir"));
Process p = pb.start();
票数 12
EN

Stack Overflow用户

发布于 2015-08-25 20:27:19

运行文件的另一种方法如下:

代码语言:javascript
复制
import java.awt.Desktop;
import java.io.File;

public static void open(String targetFilePath) throws IOException
{
    Desktop desktop = Desktop.getDesktop();

    desktop.open(new File(targetFilePath));
}
票数 7
EN

Stack Overflow用户

发布于 2015-07-30 16:45:12

使用java通过命令行运行bat或任何其他程序的标准代码为:

代码语言:javascript
复制
runtimeProcess = Runtime.getRuntime().exec("cmd /c start cmd.exe /C\""+backup_path+"\"");
int processComplete = runtimeProcess.waitFor();

你可以使用分隔符继续多个文件,如:

票数 5
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/10685893

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档