如何使用ProcessBuilder在Java中启动带空格的快捷方式

时间:2012-09-12 00:12:27

标签: java execute processbuilder desktop-shortcut

这是我通常用来执行快捷方式文件(.lnk)的代码

  //Get Directory
  String currentDir = new File(game.getGamePath()).getCanonicalPath();

  //Parse Directory to put apostrophes around shortcut name    
  currentDir = currentDir.substring(0, currentDir.lastIndexOf("\\") + 1) + '"' +                      
  currentDir.substring(currentDir.lastIndexOf("\\") + 1, currentDir.length()) + '"';

  //prep the launcher
  ProcessBuilder processBuild = new ProcessBuilder();
  processBuild.command("cmd", "/c", "start" ,"/wait", "", currentDir);

  //launch 
  Process = processBuild.start();
  try {
       Process.waitFor();
  } catch (InterruptedException ex) {

  }

问题是当快捷方式文件名有空格时,我从Windows中得到一个错误 它无法加载[WordAfterSpace.ink]

例如说我有一个值为[Desktop \ A B.lnk]

的currentDir

解析它将是[Desktop \“A B.ink”],这在命令提示符下完美运行。

问题是如果我使用上面的代码,我会得到这个错误:

  

Windows无法查找'B.ink',请确保您输入的名称正确,然后重试

1 个答案:

答案 0 :(得分:1)

使用\“在字符串中获取双引号 另外,从头开始引用整个链接而不仅仅是链接名称,因为在它之前可能有其他空格。这样可以免除麻烦。