3

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.

2 Answers 2

4

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

Sign up to request clarification or add additional context in comments.

1 Comment

yep i kind of knew this would be the only solution when writing the post... thanks for the link to commons-exec - i use just about every other commons project and didn't know about this one!?
0

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.

1 Comment

oops sorry, those strings were coming from File.getAbsolutePath so my code was right (in that respect), my post was wrong.. edited.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.