How To Run Mac OS Terminal Commands From Java (Using Runtime?)

mtrc picture mtrc · Jan 18, 2011 · Viewed 31.1k times · Source

I've been looking up ways to run external programs using Java's runtime. This works fine, for instance:

String[] cmd = {"mkdir", "test"};
Runtime.getRuntime().exec(cmd);

Creates a new directory as you would expect. Now, from a bash window in Mac I can write this:

love testgame

To run the 'Love' game engine on a folder called testgame. Now, the reason this works is because I've aliased 'love' to call the love executable. I have a feeling that this is the reason that the following does not work:

String[] cmd = {"love", "/Users/mtc06/testgame"};
Runtime.getRuntime().exec(cmd);

And nor does this (for those wondering):

String[] cmd = {"/bin/bash", "love", "/Users/mtc06/testgame"};
Runtime.getRuntime().exec(cmd);

No doubt this is either some Java idiocy on my part, or some clash with the way that aliasing works. I hand it over to your venerable intellects, SO!

UPDATE: this doesn't work either:

String[] cmd = {"/bin/sh", "/Applications/love", "/Users/michaelcook/Desktop/Playout"};
Runtime.getRuntime().exec(cmd);

The error I'm receiving is 127 from the process generated by Runtime. I'm getting that as 'command not found' wherever I research it.

Answer

mmmmmm picture mmmmmm · Jan 18, 2011

I suspect the problem you have is the path used to find your executables. It depends also if you use an OSX app or a unix cmd

If a unix cmd (or use the Unix part of an OSX app e.g. /Applications/AppName.app/Contents/MacOS/AppName) then there are two ways to fix this

  1. Put the full path to the executable in the Java code e.g.
    String[] cmd = {"/full/absolute/path/to/love", "/Users/mtc06/testgame"};

  2. Alter the path to include the executable. This depends on the method java is launched.

    a)If java is run from the command line then add the directory of the executable to the PATH environment variable.
    b) If the java program is run from the Finder the path has to be altered in ~/MacOSX/environment.plist e.g. adding /Users/mark/bin

   <?xml version="1.0" encoding="UTF-8"?>
   <!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
   <plist version="1.0">
   <dict>
      <key>PATH</key>
      <string>/Users/mark/bin:/usr/local/bin:/bin:/usr/bin:/sbin:/usr/sbin:/usr/X11R6/bin:/usr/libexec/binutils:</string>
   </dict>
   </plist>

If the app is an OSX app the you need to launch it using open so the command line is

open -a love.app "/Users/mtc06/testgame"  

so Java command is (not tested)

String[] cmd = {"/usr/bin/open", "-a" , "love.app",  "/Users/mtc06/testgame"};