使应用程序在其自己的目录中运行

时间:2009-01-19 02:44:46

标签: java runtime exec

我正在尝试使用Java脚本启动应用程序(游戏)。背后有很长的解释原因,所以我会跳过那一部分。

游戏不会运行,除非它从自己的目录执行,IE:只是告诉Java启动EXE会在游戏中产生错误。它必须从其目录中启动。

我已经用Google搜索了几个小时,似乎找不到任何真正的答案。经过大量的Google,我知道这应该是正确的:

String workingDir = "F:\\Games\\COD4\\";
String cmd = "iw3mp.exe";           

Runtime.getRuntime().exec(cmd,null,new File(workingDir));

然而,我收到此错误:

Exception in thread "main" java.io.IOException: Cannot run program "iw3mp.exe" (in directory "F:\Games\COD4"): CreateProcess error=2, The system cannot find the file specified
at java.lang.ProcessBuilder.start(Unknown Source)
at java.lang.Runtime.exec(Unknown Source)
at java.lang.Runtime.exec(Unknown Source)
at cod4launcher.main(cod4launcher.java:29)
Caused by: java.io.IOException: CreateProcess error=2, The system cannot find the file specified
at java.lang.ProcessImpl.create(Native Method)
at java.lang.ProcessImpl.<init>(Unknown Source)
at java.lang.ProcessImpl.start(Unknown Source)
... 4 more

请帮忙!感谢。

2 个答案:

答案 0 :(得分:6)

请改为尝试:

String workingDir = "F:\\Games\\COD4\\";
String cmd = workingDir + "iw3mp.exe";
Runtime.getRuntime().exec(cmd,null,new File(workingDir));

iw3mp.exe可能不在您的系统路径上,因此您必须为Java提供可执行文件的绝对路径。

答案 1 :(得分:0)

使用java.lang.ProcessBuilder#directory(java.io.File)

Processs p = 
    new ProcessBuilder(cmd).
        directory(new File(workingDir)).
        start();