Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
382 views
in Technique[技术] by (71.8m points)

java - Runtime.exec on argument containing multiple spaces

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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", "", "", "", "", "", "", "Folderfile.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       Folderfile.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!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...