Easily switch the current default Java version

Jan 27, '06 05:21:00AM

Contributed by: Anonymous

I recently downloaded and installed Apple's Java 1.5.0 update for Tiger. Unfortunately, even using the bundled Java Preferences app, I could find no easy way to change the version of Java used by the java and javac commands in Terminal. Since I develop and test Java apps on different JDK versions, this was a necessity for me.

So I wrote the following simple UNIX shell script to allow me to easily switch between the different Java versions I have installed. Simply copy the code below into a text editor like TextEdit, and make sure to save as plain text:

#!/bin/sh

cd /System/Library/Frameworks/JavaVM.framework/Versions

CURJDK="`readlink CurrentJDK`"
echo Current JDK version: $CURJDK

if [ "$1" == "" ]; then
echo Installed versions:
ls
exit
fi

VERFOUND=`ls | grep $1 | head -n 1`

if [ "$VERFOUND" != "$1" ]; then
BASE="`basename $0`"
echo Error: Could not change JDK-- version $1 not installed!
echo Run $BASE without arguments to see a list of installed versions.
exit 127
fi

echo You must now enter your Mac OS X password to change the JDK.
sudo ln -fhsv $1 CurrentJDK
Save this as setJDK (or anything else that tickles your fancy) then go into the terminal and type chmod +x setJDK in the directory where you saved the file (ideally somewhere on your path). Run it without arguments to see what versions of Java are installed. You can then set the active version by entering the version as the first command-line argument.

Comments (23)


Mac OS X Hints
http://hints.macworld.com/article.php?story=20060121171126988