Pregunta

I'm trying to run an applescript from my java program using the "osascript" command in mac terminal. The applescript works perfectly with apps with spaces in their names when I try it from terminal, like "osascript ActivateApp.scpt Google\ Chrome", but when I try to use it in java it will open an app with no spaces only. So far I've tried

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

and

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

but none of them works. Here is the applescript:

on run argv
tell application (item 1 of argv)
activate
end tell
end run
¿Fue útil?

Solución

Try:

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

The problem you're seeing is that the application name is being taken as two arguments instead of one. On the command line, escaping the space causes bash not to split based on it, but to pass it through as part of the argument. Escaping it doesn't work in Java because Java is converting the escaped space to a regular space. You might be able to get the escape treated properly by doing something like "osascript pathToScript/ActivateApp.scpt Google\\ Chrome" so that the \ is passed through, but you're better off quoting more carefully.

The best solution to this sort of problem is to use a library like Apache Commons Exec that supports building up a command piece by piece so that you don't have to worry about spaces inadvertently breaking up what should be a single argument, e.g.:

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);

Though it might look complex at first, doing it the right way can save you numerous headaches further down the line when some otherwise innocuous piece of input breaks something subtly.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top