Skip to Main Content

Java Programming

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Runtime.getRuntime.exec() problem when path contains spaces

807605Jul 26 2006 — edited Aug 9 2007
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! :)
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Sep 6 2007
Added on Jul 26 2006
15 comments
1,530 views