Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
366 views
in Technique[技术] by (71.8m points)

java - 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
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...