从java更改命令的工作目录

我需要从我在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文件移动到root并修复其内容,问题也不会消失。 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 ); 

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

使用此forms的exec方法指定工作目录

 public Process exec(String[] cmdarray, String[] envp, File dir) throws IOException 

工作目录是第三个参数。 如果您不需要设置任何特殊环境, envp传递null

还有这种方便的方法 :

 public Process exec(String command, String[] envp, File dir) throws IOException 

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

我在我的项目中遇到了同样的问题,我尝试了关于ProcessBuilder.directory(myDir)解决方案和来自Runtime的exec方法,我的所有托盘都失败了。
这让我明白Runtime对工作目录及其子目录只有有限的权限。

所以我的解决方案很丑,但工作得很好。
我在工作目录的“运行时”中创建一个临时的.bat文件。
该文件包含两行命令:
1.移动到所需目录(cd命令)。
2.执行需要的命令。
我使用临时的.bat文件作为命令从Runtime调用exec。
这对我很有用!