Как установить java на linux
Перейти к содержимому

Как установить java на linux

  • автор:

Как установить java на linux

This topic describes the installation procedures of the JDK on the Linux platform, along with the system requirements.

General Notes About Installing the JDK on Linux Platforms from Archive Files

Installing the JDK automatically creates a directory called jdk–feature.interim.update.patch where feature ( 20 ),interim, update, and patch represent corresponding values of version information.

If you install JDK in a specific location such as /opt , you must log in with root credentials to gain the necessary permissions. If you do not have the root access, either install the JDK in your home directory or a sub directory for which you have the write permissions.

If you install the software in a directory that contains a sub directory named jdk– 20 .interim.update.patch , the new software overwrites files of the same name in that directory. Ensure that you rename the old directory if it contains files that you would like to keep.

Installing the JDK from archive files doesn’t configure the backing store for the system node of Java Preferences API ( java.util.prefs Java package). If this functionality of the JDK is required, you need to manually configure it by making sure either /etc/.java/.systemPrefs or jdk– 20 .interim.update.patch/.systemPrefs directory exists.

General Notes About Installing the JDK on Linux Platforms from RPM packages

This topic describes general information about installing JDK 20 from RPM packages on Linux platforms.

You can install only one version of JDK of the same feature release. If you try to install the newer version of the same feature release while the older version exists, the installer uninstalls the older version and installs the new version. For example, you can’t install jdk- 20 and jdk- 20 .0.1 simultaneously. If you attempt to install jdk- 20 .0.1 after jdk- 20 is installed, the installer uninstalls jdk- 20 and installs jdk- 20 .0.1 .

All versions of JDK of the same feature release are installed in /usr/lib/jvm/jdk- 20 -oracle-<ARCH> directory, where <ARCH> equals x64 or aarch64 . Additionally /usr/java/jdk- 20 symbolic link pointing to the installation directory is created for backward compatibility.

If you install an older version of a JDK when the newer version of the same feature family already exists, an error is displayed, prompting you to uninstall a newer JDK version if an older version has to be installed.

You must log in with root credentials to install or update JDK.

By default, the installation script configures the system such that the backing store for the system node of Java Preferences API (java.util.prefs Java package) is configured in /etc/.java/.systemPrefs directory.

The JDK installation is integrated with the alternatives framework. After installation, the alternatives framework is updated to reflect the binaries from the recently installed JDK. Java commands such as java , javac , javadoc , and javap can be called from the command line.

Using the java -version command, you can confirm the default (recently installed) JDK version.

System Requirements for Installing JDK on Linux Platforms

See Oracle JDK Certified Systems Configurations for information about supported platforms, operating systems, and browsers.

Installing the JDK on Linux from Archive Files, RPM Packages and Oracle Linux Repositories

You can install the JDK on a Linux platform from archive files, downloadable Red Hat Package Manager (RPM) packages files, or RPM packages from Oracle Linux (OL) repositories.

Installation can be performed by using one of the following processes:

From archive files ( .tar.gz ): This allows you to install a private version of the JDK for the current user into any location, without affecting other JDK installations. However, it may involve manual steps to get some of the features to work. See the following table for the options available for downloading and installing the JDK from archive files. The bundles are available for Linux x64 and Linux aarch64 (64-bit ARM) systems. Install the required bundle.

From downloadable RPM packages ( .rpm ): This allows you to perform a system-wide JDK installation on RPM-based Linux platforms for all users, and requires root access. See the following table for the options available for downloading and installing the JDK from Linux x64 and Linux aarch64 (64-bit ARM) RPM packages.

From Oracle Linux repositories : This allows you to perform a system-wide JDK installation on OL platforms starting from OL7 for all users, and requires root access. JDK RPM packages in Oracle Linux RPM repositories are available for x64 and aarch64 (64-bit ARM) OL platforms. Explicit download of JDK RPM packages is not required, the package manager will do it automatically for you.

Table 3-1 Difference between Generic Linux and OL platforms

JDK image is split into two packages: jdk- 20 -headless and jdk- 20 -headful .

  • jdk- 20 -headless is a headless Java Runtime for running non-GUI applications.
  • jdk- 20 -headful is headful Java Runtime and Development Tools for developing and running all types of applications.

jdk- 20 -headful package requires jdk- 20 -headless package. When these packages are installed together, they provide the same functionality as the jdk- 20 package for Generic Linux Platforms.

jdk- 20 -headless package registers java group with the alternatives framework.

jdk- 20 -headful package registers javac group with the alternatives framework.

Downloading the JDK Installer

Access Java SE Downloads page and click Accept License Agreement . Under the Download menu, click the Download link corresponding your requirement.

The following table lists the options and instructions for downloading and installing the JDK 20 release on a Linux platform:

Download File Instructions Architecture (CPU Type) Who Can Install
For Linux x64 systems: jdk- 20 .interim.update.patch_linux-x64.tar.gz Installing the 64-Bit JDK on Linux Platforms Intel — 64-bit Anyone
For Linux aarch64 (64-bit ARM) systems: jdk- 20 .interim.update.patch_linux-aarch64.tar.gz Installing the 64-Bit JDK on Linux Platforms ARM — 64-bit Anyone
For Linux x64 systems: jdk- 20 .interim.update.patch_linux-x64.rpm Installing the 64-Bit JDK on RPM-Based Linux Platforms Intel — 64-bit RPM-based Linux Root
For Linux aarch64 (64-bit ARM) systems: jdk- 20 .interim.update.patch_linux-aarch64.rpm Installing the 64-Bit JDK on RPM-Based Linux Platforms ARM — 64-bit RPM-based Linux Root
Installing the 64-Bit JDK on Linux Platforms

You can install the JDK for 64-bit Linux from an archive file ( .tar.gz ). The .tar.gz archive file (also called a tarball) is a file that can be uncompressed and extracted in a single step.

  1. Download the required file:
  • For Linux x64 systems: jdk- 20 .interim.update.patch_linux-x64_bin.tar.gz . For example jdk- 20 _linux-x64_bin.tar.gz
  • For Linux aarch64 (64-bit ARM) systems: jdk- 20 .interim.update.patch_linux-aarch64_bin.tar.gz . For example, jdk- 20 _linux-aarch64_bin.tar.gz

Before you download a file, you must accept the license agreement. Anyone (not only root users) can install the archive file in any location having write access.

$ tar zxvf jdk- 20 _linux-x64_bin.tar.gz

$ tar zxvf jdk- 20 _linux-aarch64_bin.tar.gz

The Java Development Kit files are installed in a directory named jdk- 20 .interim.update.patch .

Installing the 64-Bit JDK on RPM-Based Linux Platforms

You can install the JDK on 64-bit RPM-based Linux platforms, such as Red Hat and SuSE by using a downloadable RPM package file ( .rpm ) in the system location.

You can install the JDK using a downloadable RPM package file on an OL system too, but the preferred way to install the JDK on OL systems is from Oracle Linux RPM repositories.

  1. Download the required file:
  • For x64 systems: jdk- 20 .interim.update.patch_linux-x64_bin.rpm . For example, jdk- 20 _linux-x64_bin.rpm
  • For aarch64 (64-bit ARM) systems: jdk- 20 .interim.update.patch_linux-aarch64_bin.rpm . For example, jdk- 20 _linux-aarch64_bin.rpm

Before you download a file, you must accept the license agreement.

$ sudo rpm -ivh jdk- 20 _linux-x64_bin.rpm

$ sudo rpm -ivh jdk- 20 _linux-aarch64_bin.rpm

Upgrade the required package using the following command:

$ sudo rpm -Uvh jdk- 20 _linux-x64_bin.rpm

$ sudo rpm -Uvh jdk- 20 _linux-aarch64_bin.rpm

JDK 20 can coexist with other feature releases of JDK. For each feature release, a separate directory is created, the default directory being /usr/lib/jvm/jdk- <FEATURE> -oracle-<ARCH> . For example, JDK 20 releases for x64 will be installed in /usr/lib/jvm/jdk- 20 -oracle-x64 directory.

Installing the 64-Bit JDK on Oracle Linux Platforms

There are two OL-specific JDK RPM packages, jdk- 20 -headless and jdk- 20 -headful . When these packages are installed together, they provide full JDK functionality.

Install jdk- 20 -headless package if you only need headless Java Runtime for running non-GUI applications.

The jdk- 20 -headful package depends on jdk- 20 -headless , hence installing jdk- 20 -headful package will result in the automatic installation of jdk- 20 -headless , if it is not installed yet.

Установка Java в Linux

Java — популярный язык программирования, разработанный в компании Sun Microsystems, ныне принадлежащей корпорации Oracle. Java занимает лидирующие позиции в мире языков программирования. Многие программы, разработанные для Linux намного лучше выполняются с использованием проприетарной версии Java.

В данной статье будет рассмотрена установка JRE (Java Runtime Environment) и JDK (Java Development Kit) 8 версии on Oracle на дистрибутивы Ubuntu 20.04, CentOS 8 и Arch Linux. Также будет рассмотрен выбор необходимой среды по умолчанию.

Чем отличается JDK от JRE

  • JRE — Java Runtime Environment — это среда выполнения Java. Предназначена для обычного использования. Позволяет запускать приложения, написанные на языке Java.
  • JDK— Java Development Kit — стандартная версия платформы Java, предназначенная для разработки. Это специальный пакет разработчика, в который входят документация, различные утилиты, компилятор, библиотеки классов, а также сама JRE.

Установка Java в Ubuntu

Для начала необходимо скачать архив с официального сайта Oracle выбрав пакет с именем Linux x64 если используется 64 битная система или выбрать пакет с именем Linux если используется 32 битная система:

TJLJfuz9wzEAAAAASUVORK5CYII=

Далее скачанный архив необходимо переместить в любую директорию и распаковать. В качестве примера будет выбрана директория /usr/java/ Предварительно данную директорию необходимо создать при помощи команды:

sudo mkdir /usr/java/

Awf5x9h1Cge7AAAAAElFTkSuQmCC

Для перемещения архива необходимо выполнить следующую команду:

z+7WDMYDJHvdQAAAABJRU5ErkJggg==

(тильда) означает домашнюю директорию пользователя. Далее перейдите в директорию /usr/java и распакуйте архив при помощи команды:

sudo tar -xzvf jre-8u311-linux-x64.tar.gz

9QaKxvEOkKaSS1b8j0Tvp08v+IQ4MvfmSH2Qqe3o8f8HXC8y7UlKfEYAAAAASUVORK5CYII=

Далее системе необходимо указать, где находятся установочные файлы Java. Для этого необходимо создать символическую ссылку в каталоге /usr/bin/ которая будет ссылаться на установочную директорию /usr/java/jre1.8.0_311 Для этого необходимо выполнить команду:

sudo update-alternatives —install «/usr/bin/java» «java» «/usr/java/jre1.8.0_311/bin/java» 1

O0NJDAcmttmhKcZqLneq2gS45i58z5EjnbzyNQsTqQwN570QUdN8VTOfFRdgx7b8fwE9JnEhhFHl4wAAAABJRU5ErkJggg==

После этого можно проверить версию Java выполнив команду:

uAJAAAAAElFTkSuQmCC

Загрузите архив со средствами разработки с официального сайта компании Oracle. Необходимо выбрать раздел Linux и найти пакет с именем jdk-8u311-linux-aarch64.tar.gz:

D7GgZhvZ1heuAAAAAElFTkSuQmCC

Далее необходимо поставить галочку напротив пункта I reviewed and accept the Oracle Technology Network License Agreement for Oracle Java SE тем самым подтверждая принятия условия лицензионного соглашения.

Fese28Keg6QAAAAASUVORK5CYII=

Для скачивания файла необходимо войти в свою учетную запись Oracle или создать новую, только после этого начнется загрузка архива.

В качестве примера также будет выбрана директория /usr/java. Предварительно данная директория должна быть создана. Перенесите архив в директорию /usr/java:

wJKHqzr2cjQAAAABJRU5ErkJggg==

Далее перейдите в директорию /usr/java и распакуйте архив:

sudo tar -xzvf jdk-8u311-linux-x64.tar.gz

9wbymZsLeWgAAAABJRU5ErkJggg==

Так же, как и при настройке JRE необходимо указать, где находятся установочные файлы Java. Для этого необходимо создать символическую ссылку в каталоге /usr/bin/ которая будет ссылаться на установочную директорию /usr/java/jdk1.8.0_311. Для этого необходимо выполнить команду:

sudo update-alternatives —install /usr/bin/java java /usr/java/jdk1.8.0_311/bin/java 1

5jDAyOEAAAAASUVORK5CYII=

Переменные окружения

Многие программы используют переменную среды JAVA_HOME для того, чтобы определить расположение установки Java. Чтобы установить эту переменную для всех пользователей, сначала необходимо узнать, где именно хранится установка Java. Для этого необходимо выполнить команду:

sudo update-alternatives —config java

8H8IVE+xECxXAAAAAASUVORK5CYII=

В данном случае в системе установлены JRE и JDK одновременно. Поэтому присутствует 2 пути:

  • /usr/java/jdk1.8.0_311/bin/java
  • /usr/java/jre1.8.0_311/bin/java

Выберите нужный тип Java и скопируйте путь необходимой версии и откройте файл /etc/environment в любом текстовом редакторе (например nano):

sudo nano /etc/environment

8fEmBMz97bRJ4AAAAASUVORK5CYII=

Необходимо добавьте строку с путём установки JRE или JDK в конец этого файла:

tncR3QyKUguHjDl3x6QyHOwug1d1y9PWnDqM3f8HPohND64QrPAAAAAASUVORK5CYII=

Сохраните и закройте файл. Чтобы применить настройки, необходимо перейти в учётную запись root далее перечитать файл выполнив в терминале команду:

Установка Java в Arch Linux

В официальных репозиториях Arch Linux присутствует только OpenJDK, в то время как проприетарная JRE присутствует только в пользовательских репозиториях aur. Для установки JRE необходимо перейти по ссылке официальной страницы JRE в репозитории aur и найти ссылку на GIT репозиторий программы в поле Git Clone URL:

wFJfNkAb+2MPAAAAABJRU5ErkJggg==

Далее необходимо склонировать данный репозиторий при помощи команды:

git clone https://aur.archlinux.org/jre8.git

8LFy8UuipbQI8AAAAASUVORK5CYII=

Перейдите в скачанный репозиторий:

Для установки JRE необходимо выполнить команду:

xIu97DQV6wIrZMrmU7d56hh09asrkWpC2oL+fwBz9HzHPEFHUwAAAABJRU5ErkJggg==

При появлении фразы Proceed with installation? [Y/n] введите y и нажмите на клавишу Enter:

BafxjWnn8Uf+AAAAAElFTkSuQmCC

Установка JRE завершена.

Как и JRE JDK так же присутствует только в пользовательском репозитории aur. Несмотря на то, что установочный процесс совпадает с установкой JRE, у установки JDK есть одна особенность — с тех пор как пакеты JDK расположенные на сайте Oracle требует авторизации на сайте необходимо заранее скачать пакет JDK иначе установщик выдаст ошибку.

Перейдите на официальный сайт Oracle найдите и скачайте архив с именем jdk-8u301-linux-x64.tar.gz:

AVgXc9sCLpQnAAAAAElFTkSuQmCC

Далее склонируйте репозиторий с JDK выполнив команду:

git clone https://aur.archlinux.org/jdk8.git

MTmUtSCv1rHCsRSubkkQQUQL7B3Igmi107P8CD57nqEX0RocAAAAASUVORK5CYII=

Переместите ранее скачанный архив в только что склонированный репозиторий при помощи команды:

mv Downloads/jdk-8u301-linux-x64.tar.gz jdk8/

Где Downloads — директория куда был скачен архив, а jdk8/— директория с самим JDK. Перейдите в директорию с JDK и запустите команду для установки:

JgDZUkKIykfwpmoisG+XQhL5QaUIfycN6fvnvpkwHmJse2QYAAAAASUVORK5CYII=

При появлении фразы Proceed with installation? [Y/n] введите y и нажмите на клавишу Enter:

Je8cAAAAASUVORK5CYII=

После этого установка JDK будет завершена.

Установка Java в CentOS 8

Для RHEL дистрибутивов, таких как, CentOS, Fedora, RedHat и OpenSUSE есть официальный RPM-пакет. Для начала необходимо скачать пакет с официального сайта Oracle выбрав пакет с именем Linux RPM если используется 64 битная система или выбрать пакет с именем Linux x64 RPM если используется 32 битная система:

g+7kYXXJVOKIQAAAABJRU5ErkJggg==

Чтобы установить пакет необходимо выполнить команду в терминале:

sudo rpm -i jre-8u311-linux-x64.rpm

H+e6jWWzjgjhW9CU5Noa6zBfkfRAcluHMeCd68WTb44GVEbKWIA6rBntL8iQpbmYScmZDbVnSOVoZen8ASURNvrAw+nQxpS+25IMY9r7bBqmGwIPk8sFFwYnWqMBnsuMWp9P8PnZk0VMIhYZ0AAAAASUVORK5CYII=

После установки можно проверить версию JRE при помощи команды:

B8sb3pmw0Z8ZAAAAAElFTkSuQmCC

Средства для разработчиков также можно скачать с официального сайта Oracle выбрав пакет с именем jdk-8u311-linux-x64.rpm для 64 битной системы и выбрав пакет с именем jdk-8u311-linux-i586.rpm для 32 битной системы:

38PGAnobR9D9gAAAABJRU5ErkJggg==

Для установки из терминала, необходимо выполнить команду:

sudo rpm -i jdk-8u311-linux-x64.rpm

iT0cBhpPLkAAAAAASUVORK5CYII=

Для просмотра версии JDKнеобходимо выполнить команду:

5O1QVyR45yMAAAAAElFTkSuQmCC

Выбор версии Java по умолчанию

Ubuntu 20.04

Для начала необходимо вывести список всех установленных версий Java в системе. Для этого необходимо выполнить команду:

sudo update-alternatives —config java

8H8IVE+xECxXAAAAAASUVORK5CYII=

Если у в вас системе установлено несколько версий Java можно выбрать ту, которая будет использоваться по умолчанию. Так как на данный момент в системе присутствует только 8 версия Java то выбирать версию нет необходимости. Если в системе одновременно присутствуют 2 и более версии, то для выбора версии по умолчанию необходимо ввести цифру, которая будет располагаться напротив нужной версии.

ArchLinux

Для начала просмотрите список установленных сред при помощи команды:

archlinux -java status

shkSGrRsjuywpNQ8U8YSBakc2BNU6HXw+7tI8AoywK2EyfHiI9maSWxxb+MSpsaiwORAkWiBHDSv8XVRJsJD28xhIAAAAASUVORK5CYII=

Далее установите необходимую версию:

sudo archlinux -java set имя_среды

sudo archlinux-java set java-8-jdk

C6N0VessAcfuAAAAAElFTkSuQmCC

Для проверки версии JDK необходимо выполнить команду:

Mp6cb2kd+iLZdR57qb1k04q8eINBi+pgj0z40V9iVf9pniT8lUIMCm0DUuNE+KUro2JRrM6VGvHmkJU5mIYoDGLXCbjyJ5X4yN+X4vCng4lzn2HJMUsnesxtM0sEJWw0EWBeNcl2U1pFCw9yCVv8LO2o3urIvSXcAAAAASUVORK5CYII=

Для проверки версии JRE необходимо выполнить команду:

ALZLJr9WQoB6AAAAAElFTkSuQmCC

CentOS 8.2

Выбрать необходимую версию Java можно с помощью команды ниже (так же, как и в Ubuntu). Необходимо выбрать цифру, соответствующую номеру версии:

sudo update-alternatives —config java

wKc8JSLwIIgyQAAAABJRU5ErkJggg==

Выводы

В данной статье показан процесс установки и настройки Java в различных дистрибутивах Linux. Если остались вопросы, спрашивайте в комментариях!

Обнаружили ошибку в тексте? Сообщите мне об этом. Выделите текст с ошибкой и нажмите Ctrl+Enter.

Install the Java Runtime Environment

The Java Runtime Environment (JRE) is required to run Java programs. Nowadays there are many JRE packages available from a variety of projects and companies, but the two most popular on Ubuntu are OpenJDK and Oracle HotSpot. Using one package over the other should not create any functional difference in most applications; however, some prefer OpenJDK over Oracle HotSpot as the former does not contain closed-source components, has a much clearer licensing and support policy, and is maintained as part of the Ubuntu archive, with easier installation and upgrades.

In this guide, we’ll be going through the installation of both JRE packages. Of course, you generally only need to pick the one that best suits your needs and preferences.

What you’ll learn

  • How to install OpenJDK JRE
  • How to install Oracle HotSpot JRE

What you’ll need

  • A machine running Ubuntu

That’s all you need. If you have that, let’s proceed to the next step!

2. Installing OpenJDK JRE

With new versions of Java released every 6 months, there are multiple versions available for use. Nowadays, Java 11 is the current Long Term Support (LTS) version, but Java 8 is still widely used. Moreover, the non LTS versions of Java are bringing a steady stream of innovation into the language, and also see some adoption.

Ubuntu offers the default-jre package, which is regularly updated to ship the latest version of the current OpenJDK JRE in Long Term Support (LTS). The default-jre is an excellent choice for most situations, thanks to the outstanding track of backwards compatibility of the Java Virtual Machine.

(Alternatively, you may opt to use a specific Java version, using for example the openjdk-11-jre package; as updates are released for that version of the Java Virtual Machine, that packages will be updated, allowing you to stick to the latest and greatest update of one specific version of the Java language.)

To install the OpenJDK JRE, we run:

We can check if OpenJDK JRE was properly installed by running:

It should output the following:

(Although the output may change in the future as new Java versions are promoted to LTS status, or the current LTS version receives updates.)

In the next step we’ll install Oracle HotSpot JRE.

3. Installing Oracle HotSpot JRE

Downloading the Oracle HotSpot JRE binaries

Download JRE binaries in .tar.gz (tarball) by heading over to their website. An Oracle account is needed to download the Oracle HotSpot JRE.

Oracle does not currently offer JRE packages for Java 11 or above from their website so, for this tutorial, we will use the Oracle HotSpot JRE version to be 8u291 (Java 8, update 291).

JAVA, JDK or JRE Installation on Linux

For many purpose we need to install the java on our System, It will help to give all snapshots together for installation. For more visit to official site click here

Manish Chaubey

T here may be many ways and each individuals their own directory and path style to install the java on your Linux System but, I am going through common point of view.

Step 0: Update your System (Package Index)

Step 1: Download the JDK (Java Development Kit) Click here

From this site you may download the JDK of your own choice suitable to your system configurations.

For me it’s jdk-7u3-linux-i586.tar.gz downloaded in Downloads folder.

Step 2: Extract the .gz file by following command

Above command will make a directory named

Step 3: Made a directory named java in /usr/share/ folder

You may install your java to any directory as you wish but, for me it’s /usr/share/ folder and as I told you it’s common structure followed by Developers, use following command to make directory in usr/share/.

Step 4: Move the jdk1.8.0_161 folder to /usr/share/java folder.

Step 5: Create the Symbolic link of each jdk package by command update-alternatives as follows

Step 6: JAVA Environment variable Setup

Java environment variable can be set by two way

1 Local or user level privileges by Bash Shell ( .bashrc file of home directory) .

2 Global or root level privileges in profile script

Step 6.1: Local Environment Variable Setup

Step 6.2: Global Environment variable Setup

Global environment variable can be set to profile by following command.

Step 7: Test Your Installation

7.1 Open new terminal by Ctrl+Alt+T

7.2 java -version

So, above steps will install the java on your system.

Note:- Sometimes when run java -version show error no such directory found /usr/share/…, This is because of some dependency of the 32 bit are missing.

then, hit following command..

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *