Java платформа для linux

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

В этой статье речь пойдёт о проприетарной версии Java. Часто происходят ситуации, когда пользователь пытается открыть какую-либо программу на Java, а она либо вообще не запускается, либо пытается это сделать с помощью OpenJDK (Java Development Kit). Но вместо результата вы получаете кучу ошибок (как например с Minecraft). В данных ситуациях вам, скорее всего, поможет установка Java от Oracle.

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

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

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

Установка Java в Linux своими руками

Скачать архив с необходимой вам версией вы можете с официального сайта. Далее вам надо перенести его в желаемую директорию и распаковать. Рекомендую /opt/java, далее она и будет использоваться. Сделайте это, используя следующие команды:

sudo tar -xzf /opt/java/jre*.tar.gz

Где «*» — версия Java.

Загрузите архив со средствами разработчки с официального сайта компании Oracle. Также перенесите его в желаемую директорию и распакуйте:

sudo tar -xzf /opt/java/jdk*.tar.gz

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

JRE и JDK

Для установки проприетарной Oracle Java вам необходимо добавить репозиторий, обновить индексы пакетов и установить Java. В Ubuntu, начиная с 18 релиза, это делается автоматически после добавления репозитория.

Внимание! Будут установлены как JRE, так и JDK. Сначала добавим репозиторий и обновим списки пакетов:

sudo add-apt-repository ppa:webupd8team/java
sudo apt-get update

В процессе установки необходимо будет принять лицензионное соглашение:

sudo apt-get install oracle-java8-installer

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

В официальных репозиториях есть только OpenJDK. Поэтому придётся воспользоваться пакетом из AUR(вы можете, конечно, руками установить Java от Oracle, но AUR проще). Установка производится всего одной командой:

JDK так же можно установить, используя AUR. Просто выполните команду:

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

Для RHEL, Fedora, Cent OS, OpenSUSE есть официальный RPM-пакет, который вы можете скачать с официального сайта. Чтобы установить пакет из терминала, воспользуйтесь этой командой:

sudo rpm -i /путь/к/файлу/jre-*.rpm

где «*» — версия Java. Или же примените любую графическую утилиту.

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

Где «*» — версия Java. «

» — указывает, что путь начинается.

Выбор версии Java

Ubuntu

Для переключения на 8 версию Java используйте следующую команду:

sudo update-java-alternatives -s java-8-oracle

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

sudo apt-get install oracle-java8-set-default

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

sudo update-alternatives —install /usr/bin/java java / usr / lib / jvm / java-8-oracle/bin/java 1

sudo update-alternatives —install / usr / bin / javaс javaс / usr / lib / jvm / java-8-oracle / bin / javaс 1

sudo update-alternatives —install / usr / bin / javaws javaws / usr / lib / jvm /java-8-oracle / bin / javaws 1

Теперь осталось выбрать версии исполняемых файлов java, javaws и javac, которые будут использоваться по умолчанию:

Читайте также:  Windows right management server

sudo update-alternatives —config java

sudo update-alternatives —config javac

sudo update-alternatives —config javaws

ArchLinux

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

Затем установите необходимую вам:

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

archlinux-java set java-8-jre/jre

CentOS

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

sudo update-alternatives —config java

sudo update-alternatives —config javac

sudo update-alternatives —config javaws

Настройка переменных окружения

Чтобы настройки были доступны для всех пользователей, будем использовать файл /etc/profile. Откройте его для редактирования любым текстовым редактором с помощью команды sudo и добавьте в конец следующие строки:

  1. export JAVA_HOME=/opt/java/jdk*/
  2. export JRE_HOME=/opt/java/jdk*/jre
  3. export PATH=$PATH:/opt/java/jdk*/bin:/opt/java/jdk*/jre/bin
  • Вместо пути по умолчанию /opt/java укажите тот, который использовали;
  • Если вы используете не JDK, а JRE, то в пути у вас так же будет не «jdk*», а «jre*»;
  • «*» — версия Java, которая у вас установлена.

Выводы

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

Источник

Java платформа для linux

Java — это язык программирования и вычислительная платформа, впервые выпущенная компанией Sun Microsystems в 1995 году. Это базовая технология, на которой основываются многие современные программы (в том числе утилиты, игры и бизнес-приложения). Java работает на более чем 850 млн персональных компьютерах и в миллиардах устройств (в том числе в мобильных телефонах и в телевизорах) по всему миру.

Зачем нужен Java?

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

Версии Java

На данный момент существует множество реализаций Java платформы, из которых популярны две – открытая версия OpenJDK и Oracle Java. Основные отличия между этими версиями заключается в том, что в Oracle Java содержатся некоторые закрытые компоненты, а так же компоненты, защищенные патентами. OpenJDK является реализацией спецификаций Java с полностью открытым исходным кодом. Начиная с 7 версии OpenJDK является эталонной реализацией Java SE. Для большинства пользователей нет особой разницы какой именно версией Java пользоваться, но в некоторых случаях закрытая реализация от Oracle проявляет себя с лучшей стороны.

Установка Java

OpenJDK

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

Установить последнюю версии плагина для браузера можно перейдя по ссылке слева или введя в терминале следующую команду:

Установить последнюю версии пакета документации можно перейдя по ссылке слева или введя в терминале следующую команду:

Установка Oracle Java сторонним скриптом от проекта webupd8.org (JRE и JDK)

В связи с тем, что Oracle изменила условия распространения своей реализации Java, в репозитории Ubuntu не содержатся компоненты Oracle Java. Существует PPA организованный сайтом webupd8.org содержащий в себе программу, которая будет автоматически проверять версию Java на сайте Oracle и сравнивать её с версией установленной на вашем компьютере. Это позволяет обойти ограничения наложенные на распространение Oracle Java.

Чтобы добавить данный репозиторий и использовать последнюю версию Java с сайта Oracle, выполните в терминале следующие действия:

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

Проверьте установленную версию:

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

Переключение между версиями Java. Вы можете установить Java 7 или другую версию командой:

После этого можно переключаться между версиями Java с помощью команд. Переключение на версию Java 7:

Переключение на версию Java 8:

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

Поэтому, как вариант, если у вас нет программ использующих их, то не устанавливайте их.

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

Либо командой (добавленное командой export действует только до перезагрузки)

Переменная PATH должна зависить от JAVA_HOME и JRE_HOME, как показано в команде ниже. Команды с export должны быть набраны в консоли и тогда они будут действовать до перезагрузки системы. Или добавлены в конец файла /etc/profile и тогда они будут действовать после перезагрузки системы.

Читайте также:  Windows 10 мыльное изображение

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

Скорее всего данный скрипт именно так устанавливает переменную PATH так что вам не нужно будет её менять и нужно выполнить только последние три комманды.

Установка различных версий Java через графическое меню может быть сделана сторонним скриптом от Bruce Ingalls.

Установка скрипта из репозитория:

Либо установите вручную:

После этого запустите скрипт:

Для удаления Oracle Java 8 выполните команду:

Источник

7 JRE Installation for Linux Platforms

This page describes JRE for Linux system requirements and gives installation instructions for several JRE-Linux combinations.

This page contains these topics:

See «JDK 8 and JRE 8 Installation Start Here» for general information about installing JDK 8 and JRE 8.

For information on enhancements to JDK 8 that relate to the installer, see «Installer Enhancements in JDK 8».

System Requirements

See http://www.oracle.com/technetwork/java/javase/certconfig-2095354.html for information about supported platforms, operating systems, and browsers.

On a 64-bit system, you can download either the 64-bit or the 32-bit version of the Java platform. However, if you are using a 32-bit browser and you want to use the plugin, then you need to install the 32-bit version of the Java platform. To determine which version of Firefox you are running, launch the application, and select the menu item Help -> About Mozilla Firefox. At the bottom of the window is a version string line that contains either «Linux i686» (32-bit) or «Linux x86_64» (64-bit). To setup the Java plugin, see «Manual Installation and Registration of Java Plugin for Linux».

JRE 8 Installation Instructions

This topic contains these topics:

Installation Instruction Notation and Files

For instructions containing the notation version , substitute the appropriate JRE update version number. For example, if you are installing update JRE 8 update release 2, the following string representing the name of the bundle:

Note that, as in the preceding example, the version number is sometimes preceded with the letter u , for example, 8u2 , and sometimes it is preceded with an underbar, for example, jre1.8.0_02 .

The following table lists the options and instructions for downloading the JRE 8 release for a Linux platform.

Download File and Instructions Architecture Who Can Install
jre-8u version -linux-x64.tar.gz
«Installation of the 64-bit JRE on Linux Platforms»
64-bit anyone
j re-8u version -linux-i586.tar.gz
«Installation of the 32-bit JRE on Linux Platforms»
32-bit anyone
jre-8u version -linux-x64.rpm
«Installation of the 64-bit JRE on RPM-based Linux Platforms»
64-bit RPM-based Linux root
jre-8u version -linux-i586.rpm
«Installation of the 32-bit JRE on RPM-based Linux Platforms»
32-bit RPM-based Linux root

JDK 7u6 and later releases include JavaFX SDK (version 2.2 or later). The JavaFX SDK and Runtime are installed and integrated into the standard JDK directory structure.

Installation of the 64-bit JRE on Linux Platforms

This procedure installs the Java Runtime Environment (JRE) for 64-bit Linux, using an archive binary file ( .tar.gz ).

These instructions use the following file:

Download the file.

Before the file can be downloaded, you must accept the license agreement. The archive binary can be installed by anyone (not only root users), in any location that you can write to. However, only the root user can install the JDK into the system location.

Change directory to the location where you would like the JDK to be installed, then move the .tar.gz archive binary to the current directory.

Unpack the tarball and install the JRE.

The Java Development Kit files are installed in a directory called jdk1.8.0_ version in the current directory.

Delete the .tar.gz file if you want to save disk space.

Installation of the 64-bit JRE on RPM-based Linux Platforms

This procedure installs the Java Runtime Environment (JRE) for 64-bit RPM-based Linux platforms, such as Red Hat and SuSE, using an RPM binary file ( .rpm ) in the system location. You must be root to perform this installation.

These instructions use the following file:

Download the file.

Before the file can be downloaded, you must accept the license agreement.

Become root by running su and entering the super-user password.

Uninstall any earlier installations of the JDK packages.

Install the package.

To upgrade a package:

Delete the .rpm file if you want to save disk space.

Exit the root shell.

There is no need to reboot.

Installation of the 32-bit JRE on Linux Platforms

This procedure installs the Java Runtime Environment (JRE) for 32-bit Linux, using an archive binary file ( .tar.gz ).

These instructions use the following file:

Download the file.

Before the file can be downloaded, you must accept the license agreement. The archive binary can be installed by anyone (not only root users), in any location that you can write to. However, only the root user can install the JRE into the system location.

Change directory to the location where you would like the JRE to be installed, then move the .tar.gz archive binary to the current directory.

Unpack the tarball and install the JRE.

The JRE files are installed in a directory called jre1.8.0_ version in the current directory.

Delete the .tar.gz file if you want to save disk space.

Installation of the 32-bit JRE on RPM-based Linux Platforms

This procedure installs the Java Runtime Environment (JRE) for 32-bit RPM-based Linux platforms, such as Red Hat and SuSE, using an RPM binary file ( .rpm ) in the system location. You must be root to perform this installation.

These instructions use the following file:

Download the file.

Before the file can be downloaded, you must accept the license agreement.

Become root by running su and entering the super-user password.

Uninstall any earlier installations of the JRE packages.

Install the package.

To upgrade a package:

Exit the root shell.

There is no need to reboot.

Delete the .rpm file if you want to save disk space.

Installation of Public Key on RPM-based Linux Platforms

Since JDK version 8, the JRE RPMs are signed with OL keys. Installation of these RPMs on Linux distributions other than OL gives a warning message indicating that security validation of the package fails. This indicates that the public key used to sign this RPM needs to be installed in the system. A sample warning message and the public key installation steps are as follows:

Sample Warning Message
Installation Steps

Download the key file from https://yum.oracle.com/RPM-GPG-KEY-oracle-ol7 using the following command:

Install the key using the following command:

sudo rpm —import RPM-GPG-KEY-oracle-ol7

Public key installation needs to be done only once. The key installation is persistent across reboots.

General Installation Notes

This topic describes general installation topics.

Root Access

Installing the software automatically creates a directory called jre1.8.0_ version . Note that if you choose to install the Java SE Runtime Environment into system-wide location such as /usr/jre , you must first become root to gain the necessary permissions. If you do not have root access, simply install the Java SE Runtime Environment into your home directory, or a subdirectory that you have permission to write to.

Overwriting Files

If you install the software in a directory that contains a subdirectory named jre 1.8.0_ version , the new software overwrites files of the same name in that jre 1.8.0_ version directory. Rename the old directory if it contains files you want to keep.

System Preferences

By default, the installation script configures the system such that the backing store for system preferences is created inside the JRE’s installation directory. If the JRE is installed on a network-mounted drive, it and the system preferences can be exported for sharing with Java runtime environments on other machines.

Источник

Читайте также:  Brother установка драйвера linux
Оцените статью