Runtime.exec on argument containing multiple spaces

Minos picture Minos · Jul 14, 2011 · Viewed 21.5k times · Source

Can anyone make the following run?

public class ExecTest {
  public static void main(String[] args) {
    try {
      //Notice the multiple spaces in the argument
      String[] cmd = {"explorer.exe", "/select,\"C:\\New      Folder\\file.txt\""};

      //btw this works
      //String cmd = "explorer.exe /select,\"C:\\New Folder\\file.txt\"";

      //and surprisingly this doesn't work
      //String[] cmd = {"explorer.exe", "/select,\"C:\\New Folder\\file.txt\""};

      //Update: and (as crazy as it seems) the following also worked
      //String[] cmd = {"explorer.exe", "/select,\"C:\\New", "Folder\\file.txt\""};

      Runtime.getRuntime().exec(cmd);
    } catch (Exception e) {
        e.printStackTrace();
    }
  }
}

Using Java 6. Tested under Vista x64. By the way, taking the string that gets executed (you 'll have to use the String version of exec to get it) and using it in the Search field of Vista's start menu will run as expected.
Any help will be greatly appreciated. I'm going nuts..!

Update: I added a solution for the 2nd weird thing my post is pointing out, that the 2 versions of exec behave differently. The solution is based on the answer by prunge. Thnx again.

Answer

Minos picture Minos · Jul 16, 2011

Ok, this is not simply an update but also an answer so I'm filing it as one. According to all information I could find, the following should theoretically do it:

String[] cmd = {"explorer.exe", "/select,\"C:\New", "", "", "", "", "", "", "Folder\file.txt\""};

The multiple spaces have been broken into empty strings and the array version of exec is used. Using the above array, I debugged the loop in lines 50-75 of java.lang.ProcessImpl where a string is finally constructed. The resulting string was:

explorer.exe /select,"C:\New       Folder\file.txt"

This is what is passed as the 1st argument to ProcessImpl's native create method (line 118 same class), which as it seems fails to run properly this command.

So I guess it all ends here... sadly.

Thnx prunge for pointing out the java bug. Thnx everyone for their time and interest!