Hi all,
Firstly, I am NOT posting a question, but contributing a solution since I had this problem, which haunted me for sometime, and finally solved it.
I haven't seen (far as I could search) any solution here, so here it is!
When you do:
Runtime.getRuntime().exec("cmd /c start C:\myDir\files\myFile.doc");
I see everyone agree it works. It doesn't contain any spaces in the path.
When something like:
Runtime.getRuntime().exec("cmd /c start C:\my Dir\files\my File.doc");
this now breaks.
There had been number of suggestions around, but none worked for me.
Let me just post the code first, and explain later.
/**
* Inserts quotes at correct locations in nominated path string.
*/
public static String putQuotesAroundSpaces(String originalPath) {
StringTokenizer st = new StringTokenizer(originalPath, File.separator);
String newPath = "";
while(st.hasMoreTokens()) {
String token = st.nextToken();
if (token.contains(" ")) {
newPath += File.separator + "\"" + token + "\"";
} else {
newPath += File.separator + token;
}
}
return newPath.substring(1, newPath.length());
}
And do this:
Runtime.getRuntime().exec("cmd /c start " + putQuotesAroundSpaces(yourFile));
What's happening is that quotes are inserted at various places:
cmd /c start C:\"my Dir"\files\"my File.doc"
Please note that it is required to quote names with spaces only.
Not the whole path.
So there your go. Hope this will help others who's going/gone through the same nightmare I had!
Happy Java programming! :)