Over a million developers have joined DZone.

Running AppleScript From Java

· Java Zone

Navigate the Maze of the End-User Experience and pick up this APM Essential guide, brought to you in partnership with CA Technologies

n my current project, I need to launch an external application and maybe execute some additional commands on this external application. Due to the very nature of the project, the whole system will always be run on Mac OS X. So I thought, "why not use AppleScript"?

Turns out using AppleScript to launch applications is fairly easy, all you have to do is

tell application "name of your app" to launch

If you want to try this from the command line, osascript comes in handy:

osascript -e 'tell app "iTunes" to launch'

So far so good. Should be easy to do this from Java, shouldn't it? Turns out it's not so easy at all. Let's try this:

  String launchCmd = "osascript -e 'tell application \"iTunes\" to play'";
  process = Runtime.getRuntime().exec(launchCmd);

  BufferedReader bufferedReader = new BufferedReader(
    new InputStreamReader(process.getErrorStream()));
  while ((lsString = bufferedReader.readLine()) != null) {
    System.out.println(lsString);
  }

I'm not sure why, but it results in a nasty "0:1: syntax error: A unknown token can't go here. (-2740)" error message.

But there is another signature for Runtime.exec:

  String[] cmd = { "osascript", "-e",	"tell app \"iPhone Simulator\" to launch" };
  process = Runtime.getRuntime().exec(cmd);

  BufferedReader bufferedReader = new BufferedReader(
    new InputStreamReader(process.getErrorStream()));
  while ((lsString = bufferedReader.readLine()) != null) {
    System.out.println(lsString);
  }

... and this works out just fine!

From http://www.peterfriese.de

Thrive in the application economy with an APM model that is strategic. Be E.P.I.C. with CA APM.  Brought to you in partnership with CA Technologies.

Topics:

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}