JAVA_HOME is set to an invalid directory while run

2020-07-02 09:42发布

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

2条回答
【Aperson】
2楼-- · 2020-07-02 10:08

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
查看更多
够拽才男人
3楼-- · 2020-07-02 10:10

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
查看更多
登录 后发表回答