MacOS查看和设定JAVA_HOME


查看JAVA_HOME


在终端中输入

java -version

查看当前的java版本信息
使用下面的命令查看JAVA_HOME

echo $JAVA_HOME

如果没有输出JAVA_HOME的路径,说明还没有设置
可以继续下面的设置操作


JAVA_HOME设置


首先查找java的安装路径
我们首先想到的就是使用

which java
或者
whereis java

我们得到的结果是

/usr/bin/java

我们到finder中打开这个目录看到的并不是真正的java的安装目录
通过查找,在开发者网站找到了一篇文章

https://developer.apple.com/library/content/qa/qa1170/_index.html
Java Home

Many Java applications need to know the location of a $JAVA_HOME directory. The $JAVA_HOME on Mac OS X should be found using the /usr/libexec/java_home command line tool on Mac OS X 10.5 or later. On older Mac OS X versions where the tool does not exist, use the fixed path "/Library/Java/Home". The /usr/libexec/java_home tool dynamically finds the top Java version specified in Java Preferences for the current user. This path allows access to the bin subdirectory where command line tools such as java, javac, etc. exist as on other platforms. The tool /usr/libexec/java_home allows you to specify a particular CPU architecture and Java platform version when locating a $JAVA_HOME.

Another advantage of dynamically finding this path, as opposed to hardcoding the fixed endpoint, is that it is updated when a new version of Java is downloaded via Software Update or installed with a newer version of Mac OS X. For this reason, it is important that developers do not install files in the JDKs inside of /System, since the changes will be lost with subsequent updates by newer versions of Java.

To obtain the path to the currently executing $JAVA_HOME, use the java.home System property.

我们执行以下命令查看

/usr/libexec/java_home -V

执行结果

Matching Java Virtual Machines (1):
    1.8.0_111, x86_64:  "Java SE 8" /Library/Java/JavaVirtualMachines/jdk1.8.0_111.jdk/Contents/Home

/Library/Java/JavaVirtualMachines/jdk1.8.0_111.jdk/Contents/Home

结果中的

/Library/Java/JavaVirtualMachines/jdk1.8.0_111.jdk/Contents/Home

就是JAVA_HOME的路径
我们将JAVA_HOME的路径添加到.bash_profile中

cd #切换到当前目录下
ls -a #查看当前路径下的所有文件,主要就是看看我们要编辑的.bash_profile是不是存在

将下面的内容添加到.bash_profile的最后

export JAVA_HOME=$(/usr/libexec/java_home)
export PATH=$JAVA_HOME/bin:$PATH
export CLASS_PATH=$JAVA_HOME/lib

保存完成之后使用

source .bash_profile

更新修改的内容

现在我们再使用上面的查看JAVA_HOME的命令查看的话,就会看到以下结果的输出

/Library/Java/JavaVirtualMachines/jdk1.8.0_111.jdk/Contents/Home

你可能感兴趣的:(MacOS查看和设定JAVA_HOME)