使用Java ProcessBuilder运行本机Windows .exe生成错误::目录名无效

时间:2013-07-23 12:06:47

标签: java processbuilder

我有以下Java代码使用ProcessBuilder运行本机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

2 个答案:

答案 0 :(得分:1)

您正在使用可执行文件的完整路径作为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"};

另见

答案 1 :(得分:0)

你有没有尝试更换
pb.directory(this.file);

pb.directory(this.file.getParentFile());