从java更改命令的工作目录

use*_*723 18 java command-line batch-file working-directory

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

ROOT_DIR
|.......->com
|         |......->somepackage
|                 |.........->callerClass.java
|
|.......->resource
         |........->external.exe
Run Code Online (Sandbox Code Playgroud)

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

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

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

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

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

@echo off
echo starting process...

external.exe -i input -o output

pause
Run Code Online (Sandbox Code Playgroud)

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

Mau*_*res 24

要实现这一点,您可以使用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 );
Run Code Online (Sandbox Code Playgroud)

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


Ray*_*yek 16

使用exec方法形式指定工作目录

public Process exec(String[] cmdarray,
                    String[] envp,
                    File dir)
             throws IOException
Run Code Online (Sandbox Code Playgroud)

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

还有这种方便的方法:

public Process exec(String command,
                    String[] envp,
                    File dir)
             throws IOException
Run Code Online (Sandbox Code Playgroud)

...在一个字符串中指定命令(它只是为您转换为数组;有关详细信息,请参阅文档).