简体   繁体   中英

How to launch a Shortcut with Spaces in Java using ProcessBuilder

This is the code I would use normally to execute a Shortcut file (.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) {

  }

Problem is when the Shortcut file name has spaces I get an Error from windows saying it could not load [WordAfterSpace.ink]

For example say I had a currentDir with value [Desktop\\A B.lnk]

Parsed it would be [Desktop\\"A B.ink"] and this works perfectly on the command prompt.

problem is I would get this Error if I were to use the above code:

Windows cannot Find 'B.ink', Make sure you typed the name in correctly and try again

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM