我有以下 Java 代码来使用 ProcessBuilder 运行 native Windows .exe 文件
public class HMetis {
private String exec_name = null;
private String[] hmetis_args = {"hmetis.exe", "null", "2", "1", "10", "1", "1", "1", "0", "0"};
private Path path;
private File file;
public HMetis(String hgraph_exec, String hgraph_file) {
this.exec_name = hgraph_exec;
this.hmetis_args[1] = hgraph_file;
}
public void runHMetis() throws IOException {
this.path = Paths.get("C:\\hMetis\\1.5.3-win32");
this.file = new File(path+"\\"+this.exec_name+".exe");
ProcessBuilder pb = new ProcessBuilder(this.hmetis_args);
pb.directory(this.file);
try {
Process process = pb.start();
} finally {
// do nothing
}
}
}
运行此代码后,我收到以下错误,但从消息来看,目录名称似乎已完全形成并且正常!请问有什么建议吗?
Cannot run program "hmetis.exe" (in directory "C:\hMetis\1.5.3-win32\hmetis.exe"):CreateProcess error=267, The directory name is invalid
最佳答案
您正在使用可执行文件的完整路径作为 ProcessBuilder 的工作目录:
this.file = new File(path+"\\"+this.exec_name+".exe");
ProcessBuilder pb = new ProcessBuilder(this.hmetis_args);
pb.directory(this.file);
^
|
++++++++ "C:\hMetis\1.5.3-win32\hmetis.exe"
should be "C:\hMetis\1.5.3-win32"
但是,您只想设置工作目录,例如
pb.directory(this.path.toFile());
<小时/>
此外,ProcessBuilder.directory()
似乎没有像人们预期的那样设置“工作目录”——至少没有找到可执行文件。 ProcessBuilder can't find file?! 中描述了类似的问题。 。至少在 Windows 上,通常首先找到当前工作目录中的可执行文件(Unix 则不同)。
一个简单的修复方法是将绝对路径名添加到命令数组中,例如
String[] hmetis_args = {"C:\\hMetis\\1.5.3-win32\\hmetis.exe", "null", "2", "1", "10", "1", "1", "1", "0", "0"};
<小时/>
另请参阅
关于java - 使用 Java ProcessBuilder 运行 native Windows .exe 产生错误::目录名称无效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17809779/