- How to change the default Java version on Ubuntu
- You might also like.
- iPython R Rapid Miner
- Поиск по блогу
- Страницы
- вторник, 12 мая 2015 г.
- Как в Linux переключаться между разными версиями java?
- Сначала все выглядело вот так¶
- Как установить версию Java по умолчанию в Ubuntu / Debian
- Проверка версий Java, установленных в Ubuntu / Debian
How to change the default Java version on Ubuntu
If you are a Java developer, it is normal to have multiple Java versions installed on your machine to support different build environments. When a Java program is compiled, the build environment sets the oldest JRE version the program can support. Now, if you run this program on a Linux machine where an unsupported Java version is installed, you will encounter an exception.
For example, if your program is compiled on Java 11, it can’t be run on a machine where Java 8 is installed. But the good thing is you can install multiple Java versions on your machine and quickly change the default JRE version.
In this tutorial, I’ll explain how to change the default Java version on a Linux machine. First of all, run the following command to check the current Java version:
$ java -version openjdk version "1.8.0_191" OpenJDK Runtime Environment (build 1.8.0_191-8u191-b12-2ubuntu0.18.10.1-b12) OpenJDK 64-Bit Server VM (build 25.191-b12, mixed mode)
As you can see above, the default Java version is currently set to OpenJDK JRE 1.8. Now, let’s run the following command to see all available Java versions:
$ sudo update-alternatives --config java
Running the above command displays a list of installed Java JDKs and JREs allowing you to select the one as you want to set as default.
There are 2 choices for the alternative java (providing /usr/bin/java). Selection Path Priority Status ------------------------------------------------------------ 0 /usr/lib/jvm/java-11-openjdk-amd64/bin/java 1111 auto mode 1 /usr/lib/jvm/java-11-openjdk-amd64/bin/java 1111 manual mode * 2 /usr/lib/jvm/java-8-openjdk-amd64/jre/bin/java 1081 manual mode Press enter> to keep the current choice[*], or type selection number:
When prompted, select the Java version you would like to use. If the list does not include your desired Java version, you can always install it.
Now you can verify the default Java version as fellows:
$ java -version openjdk version "11.0.2" 2019-01-15 OpenJDK Runtime Environment (build 11.0.2+9-Ubuntu-3ubuntu118.10.3) OpenJDK 64-Bit Server VM (build 11.0.2+9-Ubuntu-3ubuntu118.10.3, mixed mode, sharing)
That’s it. The default Java version is changed to OpenJDK 11.
If you frequently switch between different Java versions, it is a good idea to write a short script to automate the process. Here is the script I used for switching to OpenJDK 8 on my machine. java8.sh
sudo update-java-alternatives -s java-1.8.0-openjdk-amd64 export JAVA_HOME=/usr/lib/jvm/java-1.8.0-openjdk-amd64/ export PATH=$PATH:$JAVA_HOME
Similarly, you can create scripts for other Java versions installed on your machine. The next step is to add these scripts as aliases to .bashrc file.
... # Java Alias alias java8='source /opt/java/switch/java8.sh' alias java11='source /opt/java/switch/java11.sh'
Read Next: How to install Java on Ubuntu 18.04 ✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.
You might also like.
iPython R Rapid Miner
В iPython мои (черновики) упражнения с Python, в разделе «Mining» собраны материалы по R, Rapid Miner, Weka, Gate. в «Projects» фрагменты старых и заготовки для новых исследований. записано для себя, открыто для всех.
Поиск по блогу
Страницы
вторник, 12 мая 2015 г.
Как в Linux переключаться между разными версиями java?
Все началось с того, что команда java -version сообщила мне, что у меня в дистрибутиве стоит 6-ая версия, а для установки нового сервера требовалась 7-я. Я года два, как не подходил к java, потому решил не умничать, а найти мануал в инете. Мануалы нашел (ссылки здесь), но оказалось, что у меня уже стоит седьмая версия, чтобы переключиться на нее, нужно было использовать update-alternatives —config java
Сначала все выглядело вот так¶
root@kali:/home/kiss# java -version java version "1.6.0_35" OpenJDK Runtime Environment (IcedTea6 1.13.7) (6b35-1.13.7-1~deb7u1) OpenJDK Server VM (build 23.25-b01, mixed mode)
Я подумал, что раз отно так, то это жжжж неспроста. В Kali полно java программ, так что мне нельзя сносить старую java. Лучше бы найти мануал, в котором все эти мелководные камни описаны. Потратил довольно много времени на всякие вредные описания oracle java и дебиановские штучки. Голова стала пухнуть, наверное поэтому от отчаяния набрал поиск на русском. И, о счастье, нашел исчерпывающий мануал (ссылка выше — Установка Java на Debian/Ubuntu/Mint).
! update-alternatives --config java
There are 2 choices for the alternative java (providing /usr/bin/java). Selection Path Priority Status ------------------------------------------------------------ 0 /usr/lib/jvm/java-6-openjdk-i386/jre/bin/java 1061 auto mode 1 /usr/lib/jvm/java-6-openjdk-i386/jre/bin/java 1061 manual mode * 2 /usr/lib/jvm/java-7-openjdk-i386/jre/bin/java 1051 manual mode Press enter to keep the current choice[*], or type selection number:
Запускаешь и переключаешься, потом снова запускаешь и уже видишь, что активна 7-ая версия, но при запуске компьютера будет активизироваться 6-ая, поскольку у нее auto mode. Мне это и надо.
java version "1.7.0_79" OpenJDK Runtime Environment (IcedTea 2.5.5) (7u79-2.5.5-1~deb7u1) OpenJDK Server VM (build 24.79-b02, mixed mode)
Ниже распечатаем справочники, дабы посмотреть при случае, что еще можно напереключать.
root@kali:/home/kiss# update-alternatives --list java /usr/lib/jvm/java-6-openjdk-i386/jre/bin/java /usr/lib/jvm/java-7-openjdk-i386/jre/bin/java
Usage: java [-options] class [args. ] (to execute a class) or java [-options] -jar jarfile [args. ] (to execute a jar file) where options include: -d32 use a 32-bit data model if available -d64 use a 64-bit data model if available -client to select the "client" VM -server to select the "server" VM -zero to select the "zero" VM -jamvm to select the "jamvm" VM -avian to select the "avian" VM -dcevm to select the "dcevm" VM -hotspot is a synonym for the "client" VM [deprecated] The default VM is server, because you are running on a server-class machine. -cp -classpath A : separated list of directories, JAR archives, and ZIP archives to search for class files. -D= set a system property -verbose:[class|gc|jni] enable verbose output -version print product version and exit -version: require the specified version to run -showversion print product version and continue -jre-restrict-search | -no-jre-restrict-search include/exclude user private JREs in the version search -? -help print this help message -X print help on non-standard options -ea[:. |:] -enableassertions[:. |:] enable assertions with specified granularity -da[:. |:] -disableassertions[:. |:] disable assertions with specified granularity -esa | -enablesystemassertions enable system assertions -dsa | -disablesystemassertions disable system assertions -agentlib:[=] load native agent library , e.g. -agentlib:hprof see also, -agentlib:jdwp=help and -agentlib:hprof=help -agentpath:[=] load native agent library by full pathname -javaagent:[=] load Java programming language agent, see java.lang.instrument -splash: show splash screen with specified image See http://www.oracle.com/technetwork/java/javase/documentation/index.html for more details.
root@kali:/home/kiss# update-alternatives --help Usage: update-alternatives [option> . ] command> Commands: --install link> name> path> priority> [--slave link> name> path>] . add a group of alternatives to the system. --remove name> path> remove path> from the name> group alternative. --remove-all name> remove name> group from the alternatives system. --auto name> switch the master link name> to automatic mode. --display name> display information about the name> group. --query name> machine parseable version of --display name>. --list name> display all targets of the name> group. --get-selections list master alternative names and their status. --set-selections read alternative status from standard input. --config name> show alternatives for the name> group and ask the user to select which one to use. --set name> path> set path> as alternative for name>. --all call --config on all alternatives. link> is the symlink pointing to /etc/alternatives/name>. (e.g. /usr/bin/pager) name> is the master name for this link group. (e.g. pager) path> is the location of one of the alternative target files. (e.g. /usr/bin/less) priority> is an integer; options with higher numbers have higher priority in automatic mode. Options: --altdir directory> change the alternatives directory. --admindir directory> change the administrative directory. --log file> change the log file. --force allow replacing files with alternative links. --skip-auto skip prompt for alternatives correctly configured in automatic mode (relevant for --config only) --verbose verbose operation, more output. --quiet quiet operation, minimal output. --help show this help message. --version show the version.
Посты чуть ниже также могут вас заинтересовать
Как установить версию Java по умолчанию в Ubuntu / Debian
В этом руководстве я покажу вам, как установить версию Java по умолчанию в Ubuntu / Debian.
Обычно в вашей системе Ubuntu или Debian запускается более одной версии Java – по причинам, связанным с разработкой или изменением требований приложений.
Предположим, что вы установили Java 11, и ранее у вас была установлена другая версия Java, вы можете выбрать версию Java по умолчанию для использования с помощью команды update-alternatives –config java.
Проверка версий Java, установленных в Ubuntu / Debian
Чтобы получить список установленных версий Java, выполните команду:
$ update-java-alternatives --list java-1.11.0-openjdk-amd64 1101 /usr/lib/jvm/java-1.11.0-openjdk-amd64 java-8-oracle 1081 /usr/lib/jvm/java-8-oracle
Получив список версий Java, установите версию по умолчанию, выполнив команду:
$ sudo update-alternatives --config java There are 2 choices for the alternative java (providing /usr/bin/java). Selection Path Priority Status ------------------------------------------------------------ 0 /usr/lib/jvm/java-11-openjdk-amd64/bin/java 1101 auto mode * 1 /usr/lib/jvm/java-11-openjdk-amd64/bin/java 1101 manual mode 2 /usr/lib/jvm/java-8-oracle/jre/bin/java 1081 manual mode Press to keep the current choice[*], or type selection number: 2
$ 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)
То же самое можно сделать для javac.
~$ sudo update-alternatives --config javac There is 1 choice for the alternative javac (providing /usr/bin/javac). Selection Path Priority Status ------------------------------------------------------------ 0 /usr/lib/jvm/java-8-oracle/bin/javac 1081 auto mode * 1 /usr/lib/jvm/java-8-oracle/bin/javac 1081 manual mode Press to keep the current choice[*], or type selection number:
Если JAVA_HOME настроен неправильно, выполните команду ниже, чтобы установить текущую настройку Java по умолчанию.
export JAVA_HOME=$(readlink -f /usr/bin/java | sed "s:bin/java::")
export JAVA_HOME=$(readlink -f /usr/bin/java | sed "s:jre/bin/java::")
Постоянство может быть достигнуто путем размещения команды экспорта в вашем .bashrc или /etc/profile