2012-07-31 55 views
0

我试图在mac终端中使用“osascript”命令从我的java程序运行一个applescript。当我尝试从终端尝试它时,applescript与名称中有空格的应用完美配合,如“osascript ActivateApp.scpt Google\ Chrome”,但是当我尝试在java中使用它时,它将打开一个不带空格的应用。到目前为止,我已经试过从Java到终端到AppleScript的空白

Runtime.getRuntime().exec("osascript pathTo/ActivateApp.scpt Google Chrome"); 

Runtime.getRuntime().exec("osascript pathTo/ActivateApp.scpt Google\ Chrome"); 

但他们没有工作。这里是AppleScript的:

on run argv 
tell application (item 1 of argv) 
activate 
end tell 
end run 

回答

0

尝试:

Runtime.getRuntime().exec("osascript pathToScript/ActivateApp.scpt 'Google Chrome'"); 

你看到的问题是,应用程序的名称被当作两个参数,而不是一个。在命令行中,转义空格会导致bash不会基于它进行拆分,而是将其作为参数的一部分传递。转义它在Java中不起作用,因为Java正在将转义空间转换为常规空间。您可能可以通过执行类似"osascript pathToScript/ActivateApp.scpt Google\\ Chrome"这样的\的方式来正确处理退出,但您最好仔细引用它。

这类问题的最佳解决方案是使用像Apache Commons Exec这样的库,它支持逐个构建一个命令,这样您就不必担心空格会无意间破坏应该是单个参数的内容,例如:

Map map = new HashMap(); 
map.put("file", new File("invoice.pdf")); 
CommandLine cmdLine = new CommandLine("AcroRd32.exe"); 
cmdLine.addArgument("/p"); 
cmdLine.addArgument("/h"); 
cmdLine.addArgument("${file}"); 
cmdLine.setSubstitutionMap(map); 
DefaultExecutor executor = new DefaultExecutor(); 
executor.setExitValue(1); 
ExecuteWatchdog watchdog = new ExecuteWatchdog(60000); 
executor.setWatchdog(watchdog); 
int exitValue = executor.execute(cmdLine); 

虽然它可能看起来复杂,首先,做正确的方式可以为您节省大量的头痛进一步向下行的时候,否则一些无关痛痒的一块投入的毁坏东西微妙。