Uzi's Blogs

Things I learn, observe and try out

Thursday, June 23, 2005

Avoiding Java Runtime exec method space problem

Typical way of executing an external process in java is using java.lang.Runtime class' exec method.

Its most comman usage is
getRuntime().exec("c:\\somefolder\\somecommand.exe");

Assume there is a space in the folder, amazingly the above form will work, for instance
getRuntime().exec("c:\\some folder\\somecommand.exe");

But this form will fail if we have two or more consective spaces, for instance
getRuntime().exec("c:\\some  folder\\somecommand.exe");
It will raise java.io.IOException.

Exception in thread "main" java.io.IOException: CreateProcess: C:\some folder\somecommand.exe error=2
at java.lang.ProcessImpl.create(Native Method)
at java.lang.ProcessImpl.(Unknown Source)
at java.lang.ProcessImpl.start(Unknown Source)
at java.lang.ProcessBuilder.start(Unknown Source)
at java.lang.Runtime.exec(Unknown Source)
at java.lang.Runtime.exec(Unknown Source)
at java.lang.Runtime.exec(Unknown Source)
...


It seems that StringTokenizer used by exec(String) method is minimizing more that one white space to single space.

The workaround is to create single element array of String holding command and pass it to exec method.

String[] command = new String[1]; //for providing arguments, create multiple elements

command[0] = "c:\\some  folder\\somecommand.exe";
getRuntime().exec(command);

and this time it works like a charm.

Keep coding in java .... :-)

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home