Search code examples
javaprocessbuilder

Using Java ProcessBuilder to run native Windows .exe producing error :: The directory name is invalid


I have the following Java code to run a native Windows .exe file using ProcessBuilder

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
        }
    }
}

after running this code I am getting the below error although from the message it seems the directory name is fully formed and OK !! Any suggestions please?

Cannot run program "hmetis.exe" (in directory "C:\hMetis\1.5.3-win32\hmetis.exe"):CreateProcess error=267, The directory name is invalid

Solution

  • You are using the complete path to the executable file as the ProcessBuilder's working directory:

    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"
    

    However, you want to set the working directory only, like

    pb.directory(this.path.toFile());
    

    In addition, it seems that ProcessBuilder.directory() does not set the "working directory" as one might expect - at least not to find the executable. A similar issue is described at ProcessBuilder can't find file?!. At least on Windows, executables in the current working directory are usually found first (Unix is a different thing).

    An easy fix would be to add the absolute path name to the command array, like

    String[] hmetis_args = {"C:\\hMetis\\1.5.3-win32\\hmetis.exe", "null", "2", "1", "10", "1", "1", "1", "0", "0"};
    

    See also