Hi everyone,
I've run into strange issues when executing OS commands from Java (running on Windows XP). The problem only occurs when there is space in the directory paths. So lets say the Java classes are located in a diretory "c:\my data\" and thre is a
import java.io.IOException;
public class MyClass {
public static void main(String[] args) {
try {
Process p = Runtime.getRuntime().exec("run.bat");
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
When you try to run this class, it will complain that the "run.bat" command does not exist.
Now create a BAT file in a directory "c:\my prog" and add it to the path. Lets say the file contains this command:
echo "prog A" > test.txt
so that it creates a test.txt file containing "prog A" in the current directory. You can execute it from the command line, and it works. But when you try to execute it from Java (which should do the same thing) you'll get an exception
java.io.IOException: Cannot run program "run.bat": CreateProcess error=2, The system cannot find the file specified
at java.lang.ProcessBuilder.start(ProcessBuilder.java:459)
at java.lang.Runtime.exec(Runtime.java:593)
at java.lang.Runtime.exec(Runtime.java:431)
at java.lang.Runtime.exec(Runtime.java:328)
at MyClass.main(MyClass.java:8)
Caused by: java.io.IOException: CreateProcess error=2, The system cannot find the file specified
at java.lang.ProcessImpl.create(Native Method)
at java.lang.ProcessImpl.<init>(ProcessImpl.java:81)
at java.lang.ProcessImpl.start(ProcessImpl.java:30)
at java.lang.ProcessBuilder.start(ProcessBuilder.java:452)
... 4 more
Well, something's rotten here :-(
Next thing - create directory "c:\my" and create a copy of run.bat in it, just change the contents to
echo "prog B" > test.txt
and then add this directory to the PATH so that it contains 'c:\my prog' and then 'c:\my'. When the 'run.bat' is executed from a command line, everything works as expected - the "c:\my prog\run.bat" is executed (as the directory is first in the PATH) and a file test.txt is created with "prog A" in it.
Now lets see what happens in the Java version - it does not fail (which is great), and the file test.txt contains "prog A" too (which is just as great). The only problem is that once you remove the c:\my\run.bat file (which is not called at all), it won't work anymore.
Any idea why this happens? Why does it depend on existence of a file that is not actually called?