Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

cannot find file using runtime.exec dir argument

Tags:

java

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 exception message is quite misleading.

like image 843
pstanton Avatar asked Feb 05 '26 23:02

pstanton


1 Answers

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

like image 58
Jon Freedman Avatar answered Feb 09 '26 00:02

Jon Freedman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!