java - 从java更改命令的工作目录

标签 java command-line batch-file working-directory

我需要从我的 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/

相关文章:

java - java 帮助中的命令行参数

linux - 是否有用于 'mapping' 的 unix 命令行实用程序?

java - ant 将所有参数传递给 java 任务

java - Play 框架中的远程处理

java - 在 Eclipse 中的 GaeNature、Google App Engine 中运行构建器时出错

windows - 拆分路径并在批处理脚本中获取最后一个文件夹名称

javascript - 启动 .bat 或 .exe 客户端

windows - 将字符串解析为变量批处理脚本

java - 为什么有些东西不能在上面运行?

java - 静态空数组实例的性能优势