Java paths get linux

linux-notes.org

Не знаете как установить переменные JAVA_HOME и PATH для каждого пользователя в соответствии с вашей системой Linux? Тогда эта статья «Установка переменных JAVA_HOME / PATH в Linux» именно для Вас. Я напишу ее в качестве заметки, чтобы потом быстренько вспомнить и прописать Java_Home и Path на ОС для каждого пользователя ( если понадобится).

Установка переменных JAVA_HOME / PATH в Unix/Linux

/ .bash_profile является сценарий запуска, который обычно выполняется один раз. Это конкретный файл используется для команд, которые выполняются, когда нормальные входе пользователя в систему. Common использует для .bash_profile должны установить переменные окружения, такие как PATH, JAVA_HOME, чтобы создать псевдонимы для команд оболочки, и установить права доступа по умолчанию для вновь создаваемых файлов.

Установка JAVA_HOME / PATH для одного пользователя

Зайдите в свой аккаунт (учетную запись) и откройте файл .bash_profile в любом редакторе:

Установите JAVA_HOME как показано используя синтаксис export JAVA_HOME=

. Если ваш путь такой как у меня /usr/lib/jvm/java-1.6.0-openjdk-i386/bin/java, то тогда пропишите:
export JAVA_HOME=/usr/lib/jvm/java-1.6.0-openjdk-i386/bin/java

Чтобы установить PATH пропишите:

Замените путь /usr/java/jdk1.5.0_07 на свой. Сохраните и закройте файл. Просто выйдите и зайдите обратно (перелогиньетсь), чтобы увидеть изменения или чтобы все изменения вступили в силу, выполните команду:

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

Совет: Используйте следующую команду, чтобы узнать точный путь Java под UNIX / Linux:

Пожалуйста, обратите внимание, что файл

/.bashrc похож на

/.bash_profile но работает только для оболочки Bash и .bashrc работает для каждой новой Bash оболочки.

Установка JAVA_HOME / PATH для всех пользователей

Вам нужно добавить строки в глобальный файл конфигурации в /etc/profile ИЛИ /etc/bash.bashrc чтобы внести изменения для всех пользователей:

Добавьте переменные PATH / JAVA_PATH следующим образом:

Сохраните и закройте файл. Еще раз вам нужно ввести следующую команду, чтобы немедленно активировать настройки:

Но если не будет работать, есть еще 1 способ прописать все это дело! Сейчас я покажу как это можно сделать.

1. Устанавливаем переменные среды:

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

3. Тест, если среда Java успешно установлена, введите команду в терминале чтобы проверить работу:

Установка переменных JAVA_HOME / PATH в Unix/Linux завершена.

One thought on “ Установка переменных JAVA_HOME / PATH в Unix/Linux ”

Спасибо за гайд, работает как часы. Первых пунктов до bash_profile включительно хватило. Версия х64. Пути и названия свои. Проверил еще javac -version. Вопрос к автору. Где эту информацию искать на сайте оракла?

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

Этот сайт использует Akismet для борьбы со спамом. Узнайте, как обрабатываются ваши данные комментариев.

Источник

How To Set Java Home Path In Linux?

Java is a popular programming language and framework in the IT industry. There are a lot of applications developed with Java. Java requires Java Development Kit to develop applications. Compiled java applications can run on systems those are installed Java Runtime Environment a.k.a JRE. We will look in this post on how to set and check JRE or JDK or Java Home Path.

Installation

There are two main different versions of JDK and JRE. The original vendor is Oracle which distributes and sets standards of Java. Second is an open version of JDK and JRE that are supported by Oracle. In this post, we will install the open version named as openjdk-9-jre-headless .

Читайте также:  Установка windows ваш компьютер несколько раз перезагрузится

Installation

Check Java Status

We will look if java path already sets simple running java command which is a compiler for Java applications.

Check Java Status

Update Locate Database

This is auxiliary operation to use locate OpenJDK location we update locate database

Find JDK Location

We will look at where is JDK located and also get the JDK version. This operation can be used Oracle JDK too. Just the JDK directory name will be different.

Find JDK Location

Set Java Home

As we see there is a lot of output for JDK search we can see that the path of JDK is /usr/lib/jvm/java-9-openjdk-amd64 because it is located in usr lib. Now we will set PATH for Java

Set Java Home

Make Java Home Configuration Persistent

The previous step makes JAVA HOME available for subshells but if the system is restarted the path will be lost. So we need to make this path definition persistent. There are different methods to make persistent. We will look single and simple one. We will add path definition to the system-wide environment definition configuration. This operation requires root privileges.

An alternative method without the need for root privileges is adding Java home path definition to the normal user .bashrc file like below.

Make Java Home Configuration Persistent

Источник

Установка Java (JDK) в Windows и Linux, переменная PATH и JAVA_HOME

Java — язык общего назначения, основанных на классах, поддерживающий многопоточность и являющийся объектно-ориентированным. Программы на Java компилируются в так называемый byte-код, который в свою очередь запускается Виртуальной Машиной Java (Java Virtual Machine — JVM), независимо от архитектуры компьютера. На данный момент последняя версия Java двенадцатая.

Ниже мы рассмотрим — как установить Java на Windows и Linux. Для каждой из платформ создана своя версия JDK, JRE и JVM, хотя сами программы на Java и не меняются от платформы к платформе (что логично).

Давайте проясним несколько вещей перед тем, как мы начнем.

  • JDK (Java Development Kit) — эта штука нужна для разработчиков на Java (то есть нас) и включает в себя инструменты разработки, документирования, упаковки и так далее (в том числе компилятор Javac, Javadoc, Jar-упаковщик и дебаггер).
  • JRE (Java Runtime Environment) — сюда включены библиотеки Java, которые необходимы для запуска Java-программ. Эта штука нужна обычным пользователям и не содержит инструментов для разработки.
  • JVM (Java Virtual Machine) — это и есть сама виртуальная машина Java, которая непосредственно и запускает наши Java-программы (байткод). Ее реализация написана для множества железа и платформ.

Установка Java (JDK) в Windows

Первым делом необходимо скачать JDK с официальной страницы Oracle. В нашем случае нужна версия под Windows, в самом низу.

После установки запустите скачанный exe-файл и установите его на ваш компьютер. Как только вы это сделаете, нужно будет настроить окружение.

Перейдите в Панель управления -> Система и безопасность -> Система. На вкладке «Дополнительно» нажмите на «Переменные среды», как показано ниже:

Теперь нужно найти и дополнить переменную PATH так, чтобы она содержала путь до установленной Java. Выберите PATH и нажмите «Изменить»:

Вы увидите список уже установленных переменных. Сейчас необходимо нажать «Новый» и добавить путь, по которому установлена Java (каталог bin!). По умолчанию это обычно «C:\Program Files(x86)\Java\jdk\bin».

Читайте также:  Ultimate windows tweaker portable rus

Нажмите «Готово» (или «Ок»), сохраните настройки и на этом всё готово! Чтобы проверить, что установка прошла корректно, откройте консоль и введите:

Если вы получили сведения о версии Java, значит всё хорошо.

Установка Java (JDK) на Linux

В Linux есть несколько способов установить Java. Мы опишем самый простой и быстрый, с использование терминала. И в данном случае мы установим OpenJDK. OpenJDK — это бесплатная и свободная реализация виртуальной машины Java, причем очень популярная.

Откройте терминал и напишите команду для установки пакета:

Осталось подтвердить установку и на этом всё, Java установлена! Единственное, что меняется — это прописывание путей до компилятора.

Чтобы прописать JAVA_HOME в окружение, выполните следующую команду (только убедитесь, что такой каталог уже есть):

Чтобы прописать компилятор Java в PATH, выполните другую команду (опять же, ваши пути до Java могут отличаться от моих):

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

О том, как же всё-таки писать на Java, мы расскажем в следующий раз.

Источник

PATH and CLASSPATH

This section explains how to use the PATH and CLASSPATH environment variables on Microsoft Windows, Solaris, and Linux. Consult the installation instructions included with your installation of the Java Development Kit (JDK) software bundle for current information.

After installing the software, the JDK directory will have the structure shown below.

The bin directory contains both the compiler and the launcher.

Update the PATH Environment Variable (Microsoft Windows)

You can run Java applications just fine without setting the PATH environment variable. Or, you can optionally set it as a convenience.

Set the PATH environment variable if you want to be able to conveniently run the executables ( javac.exe , java.exe , javadoc.exe , and so on) from any directory without having to type the full path of the command. If you do not set the PATH variable, you need to specify the full path to the executable every time you run it, such as:

The PATH environment variable is a series of directories separated by semicolons ( ; ). Microsoft Windows looks for programs in the PATH directories in order, from left to right. You should have only one bin directory for the JDK in the path at a time (those following the first are ignored), so if one is already present, you can update that particular entry.

The following is an example of a PATH environment variable:

It is useful to set the PATH environment variable permanently so it will persist after rebooting. To make a permanent change to the PATH variable, use the System icon in the Control Panel. The precise procedure varies depending on the version of Windows:

Windows XP

  1. Select Start, select Control Panel. double click System, and select the Advanced tab.
  2. Click Environment Variables. In the section System Variables, find the PATH environment variable and select it. Click Edit. If the PATH environment variable does not exist, click New .
  3. In the Edit System Variable (or New System Variable) window, specify the value of the PATH environment variable. Click OK. Close all remaining windows by clicking OK.

Windows Vista:

  1. From the desktop, right click the My Computer icon.
  2. Choose Properties from the context menu.
  3. Click the Advanced tab (Advanced system settings link in Vista).
  4. Click Environment Variables. In the section System Variables, find the PATH environment variable and select it. Click Edit. If the PATH environment variable does not exist, click New .
  5. In the Edit System Variable (or New System Variable) window, specify the value of the PATH environment variable. Click OK. Close all remaining windows by clicking OK.
Читайте также:  Windows 10 всплывающее напоминание

Windows 7:

  1. From the desktop, right click the Computer icon.
  2. Choose Properties from the context menu.
  3. Click the Advanced system settings link.
  4. Click Environment Variables. In the section System Variables, find the PATH environment variable and select it. Click Edit. If the PATH environment variable does not exist, click New .
  5. In the Edit System Variable (or New System Variable) window, specify the value of the PATH environment variable. Click OK. Close all remaining windows by clicking OK.

Update the PATH Variable (Solaris and Linux)

You can run the JDK just fine without setting the PATH variable, or you can optionally set it as a convenience. However, you should set the path variable if you want to be able to run the executables ( javac , java , javadoc , and so on) from any directory without having to type the full path of the command. If you do not set the PATH variable, you need to specify the full path to the executable every time you run it, such as:

To find out if the path is properly set, execute:

This will print the version of the java tool, if it can find it. If the version is old or you get the error java: Command not found, then the path is not properly set.

To set the path permanently, set the path in your startup file.

For C shell ( csh ), edit the startup file (

For bash , edit the startup file (

For ksh , the startup file is named by the environment variable, ENV . To set the path:

For sh , edit the profile file (

Then load the startup file and verify that the path is set by repeating the java command:

For C shell ( csh ):

For ksh , bash , or sh :

Checking the CLASSPATH variable (All platforms)

The CLASSPATH variable is one way to tell applications, including the JDK tools, where to look for user classes. (Classes that are part of the JRE, JDK platform, and extensions should be defined through other means, such as the bootstrap class path or the extensions directory.)

The preferred way to specify the class path is by using the -cp command line switch. This allows the CLASSPATH to be set individually for each application without affecting other applications. Setting the CLASSPATH can be tricky and should be performed with care.

The default value of the class path is «.», meaning that only the current directory is searched. Specifying either the CLASSPATH variable or the -cp command line switch overrides this value.

To check whether CLASSPATH is set on Microsoft Windows NT/2000/XP, execute the following:

On Solaris or Linux, execute the following:

If CLASSPATH is not set you will get a CLASSPATH: Undefined variable error (Solaris or Linux) or simply %CLASSPATH% (Microsoft Windows NT/2000/XP).

To modify the CLASSPATH , use the same procedure you used for the PATH variable.

Class path wildcards allow you to include an entire directory of .jar files in the class path without explicitly naming them individually. For more information, including an explanation of class path wildcards, and a detailed description on how to clean up the CLASSPATH environment variable, see the Setting the Class Path technical note.

Источник

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