Mac OS X Applescript FAQ: How do I execute Applescript code from a Java application?
Note: The solution shown in this article works for Java 6.
The solution for Java 7 or Java 8 is different. For that solution, see my new article, How to execute AppleScript commands from Java 7 on Mac OS X.
If you ever need to run some system-specific code from a Java application on a Mac OS X system, one way to do it is to run Applescript commands from within your Java application.
It's easy to run some Applescript from Java; for a simple example, ignoring exceptions, it just takes three lines of code, like this:
Runtime runtime = Runtime.getRuntime(); String[] args = { "osascript", "-e", "tell app \"iTunes\" to play" }; Process process = runtime.exec(args);
A complete Java Applescript example program
Here's an example of a complete Java Applescript program (a Java program that runs an Applescript command). In this case I'm running the Applescript say
command, which uses a synthesizer to speak the text you pass to it (so make sure your speakers are turned on when you try this).
Here's the source code for this Java/Applescript class:
package com.devdaily.mac.applescript; import java.io.IOException; public class JavaApplescriptTest { public static void main(String[] args) { new JavaApplescriptTest(); } public JavaApplescriptTest() { Runtime runtime = Runtime.getRuntime(); String[] args = { "osascript", "-e", "tell application \"Finder\" to activate" }; try { Process process = runtime.exec(args); } catch (IOException e) { e.printStackTrace(); } } }
Other Java/Applescript command examples
Of course there are many other Applescript commands you can run from your Java programs. Here are a few more example Applescript commands you can run, in the Java form shown above:
String[] args = { "osascript", "-e", "tell app \"iTunes\" to play" }; String[] args = { "osascript", "-e", "tell app \"iTunes\" to playpause" }; String[] args = { "osascript", "-e", "say \"Good morning Al.\" using \"Victoria\"" };
Many more Applescript tutorials
I have many more examples of Applescript commands on this blog. Just search here for "applescript", and you'll find quite a few, including this Applescript tutorial about an alarm clock program.
Applescript with Java SE 6
I just read that you can take a different programming approach with Java SE 6 on the Mac OS X platform. This URL from Apple shows the new syntax you can use in Java SE 6, specifically this code:
public static void main(String[] args) throws Throwable { String script = "say \"Hello from Java\""; ScriptEngineManager mgr = new ScriptEngineManager(); ScriptEngine engine = mgr.getEngineByName("AppleScript"); engine.eval(script); }
I haven't tested that, as I don't have Java SE 6, but hey, it comes direct from Apple.