包含多个空格的参数上的Runtime.exec

Min*_*nos 8 java runtime spaces exec

任何人都可以进行以下运行吗?

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();
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

使用Java 6.在Vista x64下测试.顺便说一下,获取执行的字符串(你必须使用exec的String版本来获取它)并在Vista的开始菜单的搜索字段中使用它将按预期运行.
任何帮助将不胜感激.我疯了......

更新:我为我的帖子指出的第二个奇怪的东西添加了一个解决方案,这两个版本的exec表现不同.解决方案基于prunge的答案.Thnx再次.

Min*_*nos 6

好吧,这不仅仅是一个更新,而是一个答案,所以我把它作为一个.根据我能找到的所有信息,理论上应该做到以下几点:

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

多个空格已被分解为空字符串,并使用了exec的数组版本.使用上面的数组,我在java.lang.ProcessImpl的第50-75行调试了循环,最后构造了一个字符串.结果字符串是:

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

这是作为ProcessImpl native create方法的第一个参数传递的(第118行同一个类),因为它似乎无法正常运行此命令.

所以我想这一切都在这里结束......可悲的是.

Thnx prunge指出java bug.Thnx每个人都有他们的时间和兴趣!


use*_*421 5

除非命令行非常简单,否则请始终使用Runtime.exec(String []),而不要使用Runtime.exec(String)。


Lar*_*zan 5

奇迹,它的作品!

不要问我为什么,但是当我在互联网上经过一段时间的神经破坏研究后,我已经接近放弃并使用临时批处理文件作为解决方法,我忘了将/ select,参数添加到命令,以及谁会想到,我的Win 7 32Bit系统上的以下工作.

String param = "\"C:\\Users\\ME\\AppData\\Local\\Microsoft\\Windows\\Temporary Internet Files\\\"";
try {
    String[]commands = new String[]{"explorer.exe", param};
    Process child = Runtime.getRuntime().exec(commands);
} catch (IOException e1) {
    System.out.println("...");
}
Run Code Online (Sandbox Code Playgroud)

一般解决方案

prunge在他的帖子(http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6511002)中提到的bug数据库的解决方案对我来说很好.

原因:

显然问题在于它在实际执行命令字符串之前对java所做的一些字符的评论.你必须通过标记你的命令字符串来自己做评论,以防止错误的java一个开始行动并弄乱一切.

怎么修:

所以,在我的情况下,我必须执行以下操作(将我的命令字符串标记,以便字符串中没有空格):

String param[] = {
    "explorer.exe",
    "/select,C:\\Users\\ME\\AppData\\Local\\Microsoft\\Windows\\Temporary",
    "Internet",
    "Files\\"};

try {
    Process child = Runtime.getRuntime().exec(param);
} catch (IOException e1) {
    System.out.println("...");
}
Run Code Online (Sandbox Code Playgroud)

正如你所看到的,我基本上在一个空格出现的地方开始了一个新的字符串,因此"Temporary Internet Files"变成了"Temporary","Internet","Files".