java · 2025-03-06 0

ubuntu 使用 jenv

一、安装 jenv

jenv 用于切换 java 版本

1.下载 jenv

此时 jenv 在 ~/.jenv

git clone https://github.com/jenv/jenv.git ~/.jenv

目录下的内容有:

root@6f08eae2a86c:~/.jenv# ls
CHANGELOG.md  LICENSE  README.md  available-plugins  bin  changelog.sh  cliff.toml  completions  fish  libexec  run-tests.sh  test

2.配置环境变量

找到 ~/.bashrc 文件,加入下面内容

export JENV_HOME=$HOME/.jenv
export PATH=$JENV_HOME/bin:$PATH
eval "$(jenv init -)"

3.环境变量生效

使用 source 命令,使得环境变量生效

source ~/.bashrc

4.结果

此时可以执行了 jenv 命令

root@6f08eae2a86c:~# jenv help
Usage: jenv <command> [<args>]

Some useful jenv commands are:
   commands    List all available jenv commands
   local       Set or show the local application-specific Java version
   global      Set or show the global Java version
   shell       Set or show the shell-specific Java version
   rehash      Rehash jenv shims (run this after installing executables)
   version     Show the current Java version and its origin
   versions    List all Java versions available to jenv
   which       Display the full path to an executable
   whence      List all Java versions that contain the given executable
   add         Add JDK into jenv. A alias name will be generated by parsing "java -version"
   remove      Remove JDK installations

二、使用 jenv

1.jenv add

例如,有 java 安装位置在 /opt/jdk1.8.0_191
jenv 增加这个 java

root@6f08eae2a86c:~# jenv add /opt/jdk1.8.0_191
oracle64-1.8.0.191 added
1.8.0.191 added
1.8 added

2.jenv versions

查看有哪些 java

root@6f08eae2a86c:~# jenv versions
  1.8
  1.8.0.191
  oracle64-1.8.0.191

3.jenv global

设置全局 java 版本

root@6f08eae2a86c:~# jenv global 1.8
root@6f08eae2a86c:~# java -version
java version "1.8.0_191"
Java(TM) SE Runtime Environment (build 1.8.0_191-b12)
Java HotSpot(TM) 64-Bit Server VM (build 25.191-b12, mixed mode)
root@6f08eae2a86c:~# which java
/root/.jenv/shims/java
root@6f08eae2a86c:~# jenv versions
* 1.8 (set by /root/.jenv/version)
  1.8.0.191
  oracle64-1.8.0.191

4.jenv local

设置当前目录的 java,实际在当前目录创建了 .java-version 文件,内容是指定的 java 版本

root@6f08eae2a86c:~/t1# jenv local 1.8.0.191
root@6f08eae2a86c:~/t1# ls -a
.  ..  .java-version
root@6f08eae2a86c:~/t1# cat .java-version 
1.8.0.191
root@6f08eae2a86c:~/t1# jenv versions
  1.8
* 1.8.0.191 (set by /root/t1/.java-version)
  oracle64-1.8.0.191

5.jenv remove

移除 java

root@6f08eae2a86c:~# jenv remove oracle64-1.8.0.191
JDK oracle64-1.8.0.191 removed
root@6f08eae2a86c:~# jenv versions
* 1.8 (set by /root/.jenv/version)
  1.8.0.191