从java更改命令的工作目录

问题描述:

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

I need to execute a .exe file from a function in one of the packages I have in my java project. now the working directory is the root directory of the project for java but the .exe file in sub-directories of my project. here is how the project is organized:

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

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

Initially I tried to run the .exe file directly through:

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

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

but the problem is external .exe needs to access some files in it's own directory and keeps thinking root directory is its directory. I even tried to use .bat file to solve the problem but the same issue rises:

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

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

and the .bat file is in the same directory as the .exe file but the same issue happens. here is the content of the .bat file:

@echo off
echo starting process...

external.exe -i input -o output

pause

即使我将 .bat 文件移到 root 并修复其内容,问题也不会消失.请帮忙

even if I move .bat file to root and fix its content the problem does not go away. plz plz plz help

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

To implement this you can use the ProcessBuilder class, here's how it would look like:

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("
");
}
s.close();

int result = process.waitFor();

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

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

It's quite a bunch of code, but gives you even more control on how the process is going to be run.