开发者

cannot find file using runtime.exec dir argument

开发者 https://www.devze.com 2023-01-12 19:22 出处:网络
It\'s quite possible i\'ve misunderstood the purpose of the File dir argument in Runtime.exec(String command, String[] envp, File dir):

It's quite possible i've misunderstood the purpose of the File dir argument in Runtime.exec(String command, String[] envp, File dir): "The working directory of the new subprocess is specified by dir. If dir is null, the subprocess inherits the current working directory of the current process."

If I run Runtime.exec("C:/mydir/myfile.bat"); the script is executed (albeit with the wrong working dir)

however if I run Runtime.exec("myfile.bat", null, new File("C:/mydir")); i get the following error:

java.io.IOException: Cannot run program "myfile.bat" (in directory "C:\mydir"): CreateProcess error=2, The system cannot find the file specified
    at java.lang.ProcessBuilder.start(ProcessBuilder.java:460)
    at java.lang.Runtime.exec(Runtime.java:593)

I would assume that the dir argument sets the working directory for the new process as well as the command being executed, however maybe it just does the former. if that is the case the excep开发者_JS百科tion message is quite misleading.


How about

Runtime.exec("C:\mydir\myfile.bat", null, new File("C:\mydir"));

From ProcessBuilder.java

// It's much easier for us to create a high-quality error
// message than the low-level C code which found the problem.

Thats why you get a non specific exception - otherwise the JDK would need to implement exception handling similar to Spring's DataAccessException hierarchy handling OS specific error codes.

Edit: you may want to look at commons-exec


I do not know if it has something to do with it, but the \ is used to escape characters.

I always use forward slashes in Java and they are properly converted.

Otherwise I would recommend to always use \ i.e. double slashes to avoid mishaps like "C:\newfile" which would be C:-newline-ewfile.

0

精彩评论

暂无评论...
验证码 换一张
取 消