Install jre linux debian

Как установить Java в Debian 10 Linux

В этом руководстве мы объясним, как установить Java (OpenJDK) в Debian 10 Linux.

Java — один из самых популярных языков программирования, используемых для создания различных приложений и систем. Приложения, разработанные на Java, масштабируемы, гибки и удобны в обслуживании.

Подготовка

Существует две различные реализации Java, OpenJDK и Oracle Java, между которыми почти нет различий, за исключением того, что Oracle Java имеет несколько дополнительных коммерческих функций. Лицензия Oracle Java разрешает только некоммерческое использование программного обеспечения, такое как личное использование и использование в целях разработки.

Репозитории Debian 10 по умолчанию включают два разных пакета Java: Java Runtime Environment (JRE) и Java Development Kit (JDK). JRE включает в себя виртуальную машину Java (JVM), классы и двоичные файлы, которые позволяют запускать программы Java. Разработчики Java должны установить JDK, который включает JRE и инструменты и библиотеки для разработки / отладки, необходимые для создания приложений Java.

Если вы не уверены, какой пакет Java установить, общая рекомендация — придерживаться версии OpenJDK (JDK 11) по умолчанию. Для некоторых приложений на основе Java может потребоваться определенная версия Java, поэтому вам следует обратиться к документации приложения.

Установка OpenJDK 11

OpenJDK 11, реализация платформы Java с открытым исходным кодом, является средой разработки и выполнения Java по умолчанию в Debian 10, Buster.

Выполните следующие команды как пользователь с привилегиями sudo или root, чтобы обновить индекс пакетов и установить пакет OpenJDK 11 JDK:

sudo apt updatesudo apt install default-jdk

После завершения установки вы можете проверить это, проверив версию Java:

Результат должен выглядеть примерно так:

openjdk version "11.0.3" 2019-04-16 OpenJDK Runtime Environment (build 11.0.3+7-post-Debian-5) OpenJDK 64-Bit Server VM (build 11.0.3+7-post-Debian-5, mixed mode, sharing) 

Это оно! На этом этапе вы успешно установили Java в свою систему Debian.

Установка OpenJDK 8

На момент написания предыдущая версия Java LTS 8 недоступна в официальных репозиториях Debian Buster.

Мы включим репозиторий AdoptOpenJDK , который предоставляет готовые пакеты OpenJDK.

    Начните с обновления списка пакетов и установки зависимостей, необходимых для добавления нового репозитория через HTTPS:

sudo apt update sudo apt install apt-transport-https ca-certificates wget dirmngr gnupg software-properties-common
wget -qO - https://adoptopenjdk.jfrog.io/adoptopenjdk/api/gpg/key/public | sudo apt-key add -
sudo add-apt-repository --yes https://adoptopenjdk.jfrog.io/adoptopenjdk/deb/
sudo apt update sudo apt install adoptopenjdk-8-hotspot
openjdk version "1.8.0_212" OpenJDK Runtime Environment (AdoptOpenJDK)(build 1.8.0_212-b04) OpenJDK 64-Bit Server VM (AdoptOpenJDK)(build 25.212-b04, mixed mode)

Установить версию по умолчанию

Если в вашей системе Debian установлено несколько версий Java, вы можете проверить, какая версия установлена по умолчанию, набрав:

Читайте также:  Nvidia 304 linux driver

Чтобы изменить версию по умолчанию, используйте команду update-alternatives :

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 1111 auto mode 1 /usr/lib/jvm/adoptopenjdk-8-hotspot-amd64/bin/java 1081 manual mode 2 /usr/lib/jvm/java-11-openjdk-amd64/bin/java 1111 manual mode Press to keep the current choice[*], or type selection number: 

Вам будет представлен список всех установленных версий Java. Введите номер версии, которую вы хотите использовать по умолчанию, и нажмите Enter .

Переменная среды JAVA_HOME

Переменная среды JAVA_HOME используется некоторыми приложениями Java для определения места установки Java.

Чтобы установить переменную среды JAVA_HOME , используйте команду update-alternatives чтобы найти, где установлена Java:

sudo update-alternatives --config java

В этом примере пути установки следующие:

  • OpenJDK 11 находится в /usr/lib/jvm/java-11-openjdk-amd64/bin/java
  • OpenJDK 8 находится в /usr/lib/jvm/adoptopenjdk-8-hotspot-amd64/bin/java

Найдя путь к предпочтительной установке Java, откройте файл /etc/environment :

Предполагая, что вы хотите установить JAVA_HOME на OpenJDK 11, добавьте следующую строку в конец файла:

JAVA_HOME="/usr/lib/jvm/java-11-openjdk-amd64" 

Чтобы изменения вступили в силу в вашей текущей оболочке, вы можете либо выйти из системы и войти в систему, либо выполнить следующую исходную команду :

Убедитесь, что переменная среды JAVA_HOME была правильно установлена:

Вы должны увидеть путь к установке Java:

/usr/lib/jvm/java-11-openjdk-amd64 

/etc/environment — это общесистемный файл конфигурации, который используется всеми пользователями. Если вы хотите установить переменную JAVA_HOME для каждого пользователя, добавьте эту строку в .bashrc или любой другой файл конфигурации, который загружается при входе пользователя в систему.

Удалить Java

Вы можете удалить Java, как любой другой пакет, установленный с помощью apt .

Например, чтобы удалить пакет default-jdk , просто запустите:

sudo apt remove default-jdk

Выводы

Последняя LTS-версия OpenJDK доступна в репозиториях Debian 10 Buster по умолчанию, и установка является простой и понятной задачей.

Если у вас есть вопросы, не стесняйтесь оставлять комментарии.

Источник

How To Install Java with Apt-Get on Debian 8

How To Install Java with Apt-Get on Debian 8

The programming language Java and the Java virtual machine or JVM are used extensively and required for many kinds of software.

This tutorial provides different ways of installing Java on Debian 8: you can download the Default JRE or JDK or the Oracle JDK. If you decide to install multiple versions of Oracle Java, you can follow the section on managing Java. The last section outlines setting the JAVA_HOME environment variable

Prerequisites

To follow this tutorial, you will need:

Installing the Default JRE/JDK

The easiest option for installing Java is using the version packaged with Debian. Specifically, this will install OpenJDK 8, the latest and recommended version.

First, update the package index.

Next, install Java. Specifically, this command will install the Java Runtime Environment (JRE).

Читайте также:  Лучшая ide python linux

When prompted, type y for yes to confirm the installation.

There is another default Java installation called the JDK (Java Development Kit). The JDK is usually only needed if you are going to compile Java programs or if the software that will use Java specifically requires it.

The JDK does contain the JRE, so there are no disadvantages if you install the JDK instead of the JRE, except for the larger file size.

You can install the JDK with the following command:

You now have the Java Runtime Environment or the Java Development Kit installed.

Installing the Oracle JDK

If you want to install the Oracle JDK, which is the official version distributed by Oracle, you’ll need to follow a few more steps. You’ll first need to install the software-properties-common package in order to use the apt-get-repository command. This will work to add the repository to your sources list and import the associated key.

When prompted to confirm the installation, type y for yes.

To ensure that we get the correct source line on Debian, we’ll need to run the following command that also modifies the line:

Once we do that we’ll need to update:

Now we’ll go through the installation process of different versions of Java. You can decide which versions you would like to install, and can choose to install one or several. Because it’s the latest stable release, Oracle JDK 8 is the recommended version at the time of writing.

Oracle JDK 8

Oracle JDK 8 is the latest stable version of Java at time of writing. You can install it using the following command:

Again, you’ll be prompted to type y to confirm the install. You’ll also be required to accept the Oracle Binary Code license terms. Use the arrow key to select “Yes”, then press “Enter” to accept the license. Once the installation is complete, you can verify your Java version:

You’ll receive output similar to this:

At this point, you have Oracle JDK 8 installed, but you may want to also install one or more of the versions below. If you’re ready to get started, skip down to the Managing Java section below.

Oracle JDK 9

Oracle JDK 9 is currently available for early access through its developer preview. The general release is scheduled for summer 2017. There is more information about Java 9 on the official JDK 9 website.

To install JDK 9, use the following command:

While it may be worth investigating Oracle JDK 9, there may still be security issues and bugs, so you should opt for Oracle JDK 8 as your default version.

Читайте также:  Linux терминал листать вверх

Managing Java

There can be multiple Java installations on one server. You can configure which version is the default for use in the command line by using update-alternatives , which manages which symbolic links are used for different commands.

The output will look something like the following. In this case, all Java versions mentioned above were installed.

There are 4 choices for the alternative java (providing /usr/bin/java). Selection Path Priority Status ------------------------------------------------------------ 0 /usr/lib/jvm/java-9-oracle/bin/java 1091 auto mode 1 /usr/lib/jvm/java-6-oracle/jre/bin/java 1083 manual mode 2 /usr/lib/jvm/java-7-oracle/jre/bin/java 1082 manual mode 3 /usr/lib/jvm/java-8-oracle/jre/bin/java 1081 manual mode * 4 /usr/lib/jvm/java-9-oracle/bin/java 1091 manual mode Press enter to keep the current choice[*], or type selection number: Press to keep the current choice[*], or type selection number: 

If we press the enter key in this case, Java 9 will be kept as the default. We can, for example, press 3 for Java 8 and receive the following output:

Output
update-alternatives: using /usr/lib/jvm/java-8-oracle/jre/bin/java to provide /usr/bin/java (java) in manual mode

Now Java 8 would be the default. Choose the default Java version that works best for your projects.

The update-alternatives command can also be used for other Java commands, such as the compiler ( javac ), the documentation generator ( javadoc ), the JAR signing tool ( jarsigner ), and more. You can use the following command, filling in the command you want to customize.

This will give us greater control over what default version of Java to use in each case.

Setting the JAVA_HOME Environment Variable

Many programs, such as Java servers, use the JAVA_HOME environment variable to determine the Java installation location. To set this environment variable, we will first need to find out where Java is installed. You can do this by executing the same command as in the previous section:

Copy the path from your preferred installation, and then open /etc/environment using nano or your favorite text editor.

In this file, add the following line, making sure to replace the highlighted path with your own copied path.

JAVA_HOME="/usr/lib/jvm/java-8-oracle" 

Save and exit the file, and reload it.

You can now test whether the environment variable has been set by executing the following command:

This will return the path you just set.

Conclusion

You have now installed Java and know how to manage different versions of it. You can now install software which runs on Java, such as Tomcat, Jetty, Glassfish, Cassandra, or Jenkins.

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Источник

Оцените статью
Adblock
detector