19
votes

I tried running ./gradlew from an Android project directory, but I get an error of:

ERROR: JAVA_HOME is set to an invalid directory: /Library/Java/JavaVirtualMachines/jdk1.8.0_11.jdk/Contents/Home

Please set the JAVA_HOME variable in your environment to match the location of your Java installation.

Things I've tried:

  1. Navigated to /Library/Java/JavaVirtualMachines. jdk1.8.0_11.jdk exists, but so does jdk1.7.0_79.jdk

  2. which java prints out /usr/bin/java

  3. printenv prints

...

JAVA_HOME=/Library/Java/JavaVirtualMachines/jdk1.8.0_11.jdk/Contents/Home JDK_HOME=/Library/Java/JavaVirtualMachines/jdk1.8.0_11.jdk/Contents/Home

...

  1. javac -version prints javac 1.8.0_11

  2. which javac prints /usr/bin/javac

3

3 Answers

53
votes

Check if /usr/libexec/java_home exists. If it does then try running

export JAVA_HOME=`/usr/libexec/java_home`

and rerunning your gradlew build. If it works then make it permanent with

echo export "JAVA_HOME=\$(/usr/libexec/java_home)" >> ~/.bash_profile
3
votes

For me, I got that error no matter what I tried. Deleting the JAVA_HOME var worked for me.

1
votes

I have added the following to my .bash_profile to help sort out issues such as this one. This has the added benefit of being able to run setjdk {version} and switch java versions on the fly.

function setjdk() {
  if [ $# -ne 0 ]; then
   removeFromPath '/System/Library/Frameworks/JavaVM.framework/Home/bin'
   if [ -n "${JAVA_HOME+x}" ]; then
    removeFromPath $JAVA_HOME
   fi
   export JAVA_HOME=`/usr/libexec/java_home -v $@`
   export PATH=$JAVA_HOME/bin:$PATH
  fi
}

function removeFromPath() {
  export PATH=$(echo $PATH | sed -E -e "s;:$1;;" -e "s;$1:?;;")
}

#Default JDK to Java 8
setjdk 1.8