22

我需要从我的 java 项目中的一个包中的一个函数执行一个 .exe 文件。现在工作目录是 java 项目的根目录,但 .exe 文件位于我项目的子目录中。以下是项目的组织方式:

ROOT_DIR
|.......->com
|         |......->somepackage
|                 |.........->callerClass.java
|
|.......->resource
         |........->external.exe

最初我尝试通过以下方式直接运行 .exe 文件:

String command = "resources\\external.exe  -i input -o putpot";
Runtime rt = Runtime.getRuntime();
Process pr = rt.exec(command);

但问题是外部 .exe 需要访问它自己目录中的一些文件,并且一直认为根目录是它的目录。我什至尝试使用 .bat 文件来解决问题,但同样的问题出现了:

Runtime.getRuntime().exec(new String[]{"cmd.exe", "/c", "resources\\helper.bat"});

并且 .bat 文件与 .exe 文件位于同一目录中,但会发生相同的问题。这是 .bat 文件的内容:

@echo off
echo starting process...

external.exe -i input -o output

pause

即使我将 .bat 文件移动到根目录并修复其内容,问题也不会消失。请帮助

4

3 回答 3

26

要实现这一点,您可以使用 ProcessBuilder 类,如下所示:

File pathToExecutable = new File( "resources/external.exe" );
ProcessBuilder builder = new ProcessBuilder( pathToExecutable.getAbsolutePath(), "-i", "input", "-o", "output");
builder.directory( new File( "resources" ).getAbsoluteFile() ); // this is where you set the root folder for the executable to run with
builder.redirectErrorStream(true);
Process process =  builder.start();

Scanner s = new Scanner(process.getInputStream());
StringBuilder text = new StringBuilder();
while (s.hasNextLine()) {
  text.append(s.nextLine());
  text.append("\n");
}
s.close();

int result = process.waitFor();

System.out.printf( "Process exited with result %d and output %s%n", result, text );

这是一堆代码,但可以让您更好地控制进程的运行方式。

于 2011-07-25T03:45:49.037 回答
17

使用这种形式的exec方法来指定工作目录

public Process exec(String[] cmdarray,
                    String[] envp,
                    File dir)
             throws IOException

工作目录是第三个参数。如果您不需要设置任何特殊环境,您可以通过nullenvp

还有这个方便的方法

public Process exec(String command,
                    String[] envp,
                    File dir)
             throws IOException

...您在一个字符串中指定命令的位置(它只是为您变成了一个数组;有关详细信息,请参阅文档)。

于 2011-07-25T03:39:29.100 回答
1

我在我的项目中遇到了同样的问题,我尝试了这个解决方案,并且我的所有托盘都失败ProcessBuilder.directory(myDir)了 exec 方法。 这让我明白,只有工作目录及其子目录的权限有限。 所以我的解决方案很丑,但效果很好。 我在工作目录的“运行时”中创建了一个临时 .bat 文件。 该文件包括两行命令: 1. 移动到需要的目录(cd 命令)。 2. 执行需要的命令。 我用我的临时 .bat 文件作为命令 调用 exec 。 这对我很有用!Runtime
Runtime






Runtime

于 2017-02-16T18:01:10.713 回答