在 Ubuntu 中安装或者升级 OpenJDK

2,957 阅读1分钟

从 Java 8 开始,Oracle 开启了快速的更新模式,每半年都会发布一个版本更新。现在最新的版本是 Java 16,那么如何在 Ubuntu 中管理多个版本的 JDK 呢?

打开终端,输入 sudo add-apt-repository ppa:openjdk-r/ppa 命令添加软件源

$ sudo add-apt-repository ppa:openjdk-r/ppa
More info: https://launchpad.net/~openjdk-r/+archive/ubuntu/ppa
Press [ENTER] to continue or Ctrl-c to cancel adding it.
...
Fetched 39.6 kB in 2s (21.2 kB/s)
Reading package lists... Done

输入 sudo apt-get update 升级系统软件包

$ sudo apt-get update
Hit:1 http://mirrors.tuna.tsinghua.edu.cn/ubuntu focal InRelease
...
Reading package lists... Done

输入 sudo apt-get install openjdk-14-jdk 命令安装指定的 JDK 版本,在这里我选择的版本是 JDK14

$ sudo apt-get install openjdk-14-jdk
Reading package lists... Done
Building dependency tree
Reading state information... Done
...
Processing triggers for hicolor-icon-theme (0.17-2) ...
Processing triggers for mime-support (3.64ubuntu1) ...

update-alternatives 命令可以管理多个版本的 JDK,如切换 JDK 版本:

$ sudo update-alternatives --config java
There are 3 choices for the alternative java (providing /usr/bin/java).

  Selection    Path                                            Priority   Status
------------------------------------------------------------
* 0            /usr/lib/jvm/java-14-openjdk-amd64/bin/java      1411      auto mode
  1            /usr/lib/jvm/java-11-openjdk-amd64/bin/java      1111      manual mode
  2            /usr/lib/jvm/java-14-openjdk-amd64/bin/java      1411      manual mode
  3            /usr/lib/jvm/java-8-openjdk-amd64/jre/bin/java   1081      manual mode

Press <enter> to keep the current choice[*], or type selection number: 2

或者设置默认的 Java 版本:

/mnt/c/Users/vincent update-alternatives --config javac
There are 2 choices for the alternative javac (providing /usr/bin/javac).

  Selection    Path                                          Priority   Status
------------------------------------------------------------
* 0            /usr/lib/jvm/java-14-openjdk-amd64/bin/javac   1411      auto mode
  1            /usr/lib/jvm/java-14-openjdk-amd64/bin/javac   1411      manual mode
  2            /usr/lib/jvm/java-8-openjdk-amd64/bin/javac    1081      manual mode

Press <enter> to keep the current choice[*], or type selection number: 0