Over a million developers have joined DZone.

Running AppleScript From Java

· Java Zone

Discover how AppDynamics steps in to upgrade your performance game and prevent your enterprise from these top 10 Java performance problems, brought to you in partnership with AppDynamics.

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

The Java Zone is brought to you in partnership with AppDynamics. AppDynamics helps you gain the fundamentals behind application performance, and implement best practices so you can proactively analyze and act on performance problems as they arise, and more specifically with your Java applications. Start a Free Trial.

Topics:

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

{{ parent.tldr }}

{{ parent.urlSource.name }}