简体   繁体   English

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

[英]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) 这是我通常用于执行快捷方式文件(.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] 问题是快捷方式文件名包含空格时,我从Windows收到错误消息,提示它无法加载[WordAfterSpace.ink]

For example say I had a currentDir with value [Desktop\\A B.lnk] 例如,说我有一个currentDir,值为[Desktop \\ A B.lnk]

Parsed it would be [Desktop\\"A B.ink"] and this works perfectly on the command prompt. 它将解析为[Desktop \\“ A B.ink”],并且在命令提示符下可以完美运行。

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 Windows无法找到“ B.ink”,请确保输入正确的名称,然后重试

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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