我需要从我的 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 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 );
这是一大堆代码,但可以让您更好地控制流程的运行方式。
关于java - 从java更改命令的工作目录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6811522/