从 java 更改命令的工作目录

2023-11-29

我需要从我的 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 文件移至根目录并修复其内容,问题也不会消失。 plz plz 帮忙


要实现这一点,您可以使用 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 );

这是相当多的代码,但可以让您更好地控制流程的运行方式。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

从 java 更改命令的工作目录 的相关文章

随机推荐