从java更改命令的工作目录
我需要从java项目中的一个包中的函数执行.exe文件。现在,工作目录是java项目的根目录,而不是项目子目录中的.exe文件。以下是项目的组织方式:从java更改命令的工作目录,java,command-line,batch-file,working-directory,Java,Command Line,Batch File,Working Directory,我需要从java项目中的一个包中的函数执行.exe文件。现在,工作目录是java项目的根目录,而不是项目子目录中的.exe文件。以下是项目的组织方式: ROOT_DIR |.......->com | |......->somepackage | |.........->callerClass.java | |.......->resource |........->external.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);
但问题是external.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 help用于指定工作目录
public Process exec(String[] cmdarray,
String[] envp,
File dir)
throws IOException
工作目录是第三个参数。如果不需要设置任何特殊环境,可以为envp
传递null
还有:
…在一个字符串中指定命令(它只是为您转换为一个数组;有关详细信息,请参阅文档)。要实现此功能,可以使用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 );
这是相当多的代码,但让您能够更好地控制流程的运行方式。我在项目中遇到了同样的问题,我尝试了有关
ProcessBuilder.directory(myDir)
和Runtime
中的exec方法的解决方案,但我所有的托盘都失败了这让我明白,
运行时
仅对工作目录及其子目录具有有限的权限所以我的解决方案很难看,但效果很好
我在工作目录的“runtime”中创建了一个临时的.bat文件
此文件包括两行命令:
1.移动到所需目录(cd命令)
2.在需要时执行命令
我使用临时.bat文件作为命令从运行时调用exec
这对我来说很有用 这看起来很合理,但我不相信有更简单的方法来达到预期的效果
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 );