Rookie
Rookie

Reputation: 1879

ProcessBuilder can't find file?!

Another question in quick succession but this has to be a really obvious error that I am not seeing. I've written some code to run a batch file below but I'm getting an error message saying it cannot find the file but I can assure you that the file does exist in the directory!

public class Pull {

public void pullData() throws IOException {
    ProcessBuilder pb = new ProcessBuilder("adb.bat");
    File f = new File("C:\\");
    pb.directory(f);
    Process p = pb.start();  
}

 public static void main(String[] args) throws IOException {
     Pull pull = new Pull();
     pull.pullData();
 }

}

and here is the error message

Exception in thread "main" java.io.IOException: Cannot run program "adb.bat" (in directory "C:\"): CreateProcess error=2, The system cannot find the file specified

Upvotes: 12

Views: 20562

Answers (2)

aretai
aretai

Reputation: 1641

Hi try to use the tutorial here - http://www.javabeat.net/examples/2007/08/21/using-the-new-process-builder-class/. Using it I have changed your class a bit and it finds the file (note that I don't know what is inside so can't fully test it). It compiles and runs without problem, while your own I experience same problems as you:

public class Pull {


public void pullData() throws IOException {
    /*ProcessBuilder pb = new ProcessBuilder("adb.bat");
    File f = new File("C:\\");
    pb.directory(f);
    Process p = pb.start(); 
    */
    ProcessBuilder p = new ProcessBuilder("C:\\adb.bat");
     p.start();
    System.out.println(p.toString());
}


 public static void main(String[] args) throws IOException {


     Pull pull = new Pull();
     pull.pullData();

 }


}

Upvotes: 2

Ash
Ash

Reputation: 9426

I'm running Linux, but the same error occurs when I run your code (modified to run a .sh rather than .bat).

Try:

ProcessBuilder pb = new ProcessBuilder("c:\\adb.bat");

Apparently using ProcessBuilder.directory doesn't affect the working directory (for the purposes of discovering the executable) that was chosen when the builder was constructed (at least, that's what seems to happen. The docs say it will change the working directory, so I guess input/output files might be relative to that?)

I'm not sure what it's actually doing internally, but providing the path to the executable in the constructor fixed the problem.

This post talks about the problem and this solution, but also raises whether environment variables have to be set, of which "path"-like variables might be useful to help ProcessBuilder discover an executable.

Upvotes: 13

Related Questions