Samuel
Samuel

Reputation: 18586

Best way to execute AppleScript from Java

I have a couple of AppleScripts that i want to run from Java. I have several options including:

  • Running the AppleScript as a string using the AppleScript ScriptEngine (using ((new ScriptEngineManager()).getEngineByName("AppleScript")).eval(scriptString)))
  • Saving the AppleScript as an Application and running the app from Java (using Desktop.getDesktop().open("name.app"))
  • Those two seemed the best options to me and I was wondering

  • Is there a better way?
  • If !(1.) Which of these two ways is the best? (Speedwise)
  • If !(1.) Are there ways to improve my methods?
  • Upvotes: 6

    Views: 2060

    Answers (3)

    RyanWilcox
    RyanWilcox

    Reputation: 13972

    I would guess that option 1 might be your best bet, because of how Applescript works.

    There are two types of Applescript: plain text Applescript, then compiled Applescript. Complied Applescript has been translated (essentially) into bytecode by the Applescript complier.

    Thus, if your application allows it, you may consider compiling all your Applescripts once, then calling them later. This will save you some time (seconds?).

    (I'm just guessing here that, in addition to the eval command, your Java class has a way to just compile Applescript.)

    During the compilation stage, Applescript also tries to identify all the applications the script uses. I believe it's during this phase where Applescript might say, "I'm sorry, I can't find SurfWriter, please point me to the app". This kind of user experience is one of those things the user wants to do as little as possible ;)

    Upvotes: 1

    Monolo
    Monolo

    Reputation: 18253

    Your first option sounds right to me, but if for some reason you want to run it as an external script, you could consider running an osascript the same way you would run a shell script.

    Upvotes: 1

    Gareth Davis
    Gareth Davis

    Reputation: 28069

    Not sure I would go with 2, that seems like a very big hammer.

    The other old style solution was to exec 'osascript' command.

    As far as I know using the script engine support is the preferred method.

    Upvotes: 1

    Related Questions