How to set java home linux

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 .

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

Источник

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 Variable in Ubuntu Linux Correctly

Last updated September 11, 2021 By Abhishek Prakash 17 Comments

Читайте также:  Рейтинг linux для сервера

If you are running Java programs on Ubuntu using Eclipse, Maven or Netbeans etc, you’ll need to set JAVA_HOME to your path. Otherwise, your system will complain that “java_home environment variable is not set”.

In this beginner’s tutorial, I’ll show the steps to correctly set Java Home variable on Ubuntu. The steps should be valid for most other Linux distributions as well.

The process consists of these steps:

  • Making sure Java Development Kit (JDK) is installed.
  • Finding the correct location of JDK executable.
  • Setting the JAVA_HOME variable and making the change permanent.

Step 1: Check if JDK is installed

The simplest way to check if Java Development Kit (JDK) is installed on your Linux system is by running this command:

The above command checks the version of Java compiler. If it is installed, it will show the Java version.

If the command shows an error like javac command not found, you’ll have to install JDK.

If Java Compiler is not installed on your system, install Java Development Kit using this command:

This will install the default Java version in your current Ubuntu version. If you need some other specific Java version, you’ll have to specify it while installing Java on Ubuntu.

Once you have made sure that Java Compiler is present on your system, it’s time to find its location.

Step 2: Get the location of JDK executable (Java Compiler)

The executable is usually located in the /usr/lib/jvm directory. I won’t left you on your own for a guessing game. Instead, let’s find out the path of the Java executable.

Use the which command to get the location of Java Compiler executable:

The problem here is that the location it gives is actually a symbolic link. You’ll have to follow it a couple of times:

And when you find a path like /usr/lib/jvm/java-11-openjdk-amd64/bin/javac, you remove the /bin/javac from it to get something like /usr/lib/jvm/java-11-openjdk-amd64

An easier method is to follow the symbolic link and get to the actual executable file directly using this command:

The readlink command follows a symbolic link. I have used ` around which java. This is called command substitution and it replaces the command with its output. Sed is then used to replace /bin/javac by nothing and thus removing it altogether.

In my example, the location of the executable file is /usr/lib/jvm/java-11-openjdk-amd64. It could be different for you. Copy the correct path you got from the above command in your system. You know, you can copy paste in the Ubuntu terminal.

Step 3: Setting JAVA_HOME variable

Now that you have got the location, use it to set the JAVA_HOME environment variable:

Check the value of JAVA_HOME directory:

Try to run your program or project in the SAME TERMINAL and see if it works.

This is not over yet. The JAVA_HOME variable you just declared is temporary. If you close the terminal or start a new session, it will be empty again.

To set JAVA_HOME variable ‘permanently’, you should add it to the bashrc file in your home directory.

You can use the Nano editor for editing files in the Linux terminal. If you do not want that and take a simple copy-paste approach, use the following commands:

Back up your bashrc file (in case you mess it, you can get it back):

Next, use the echo command to append the export command you used at the beginning of this section. Change the command below to use the correct path as displayed by your system in.

Verify that it has been correctly added to the end of the file:

The above tail command will show the last 3 lines of the specified file.

Here’s the entire output of the above three commands.

Now, even if you exit the session or restart the system, the JAVA_HOME variable will still be set to the value you specified. That’s what you want, right?

Do note that if you change the default Java version in the future, you’ll have to change the value of JAVA_HOME and point it to the correct executable path.

I hope this tutorial not only helped you to set Java Home, it also taught you how you are doing it.

If you are still facing issues or have any questions or suggestions, please let me know in the comments.

Like what you read? Please share it with others.

Источник

How to Set JAVA_HOME / PATH variables Under Linux Bash Profile

I just need a help to show me how to setup java path on Linux. How can I set JAVA_HOME and PATH variables for every user under my Linux system?

/.bash_profile is a startup script which generally runs once. This particular file is used for commands which run when the normal user logs in. Common uses for .bash_profile are to set environment variables such as PATH, JAVA_HOME, to create aliases for shell commands, and to set the default permissions for newly created files.

Set JAVA_HOME / PATH for a single user

Login to your account and open .bash_profile file
$ vi

/.bash_profile
Set JAVA_HOME as follows using syntax export JAVA_HOME=

Читайте также:  Install linux header ubuntu

. If your path is set to /usr/java/jdk1.5.0_07/bin/java, set it as follows:
export JAVA_HOME=/usr/java/jdk1.5.0_07/bin/java
Set PATH as follows:
export PATH=$PATH:/usr/java/jdk1.5.0_07/bin
Feel free to replace /usr/java/jdk1.5.0_07 as per your setup. Save and close the file. Just logout and login back to see new changes. Alternatively, type the following command to activate the new path settings immediately:
$ source

/.bash_profile
Verify new settings:
$ echo $JAVA_HOME
$ echo $PATH
Tip: Use the following command to find out exact path to which java executable under UNIX / Linux:
$ which java

Please note that the file

/.bashrc is similar, with the exception that

/.bash_profile runs only for Bash login shells and .bashrc runs for every new Bash shell.

  • No ads and tracking
  • In-depth guides for developers and sysadmins at Opensourceflare✨
  • Join my Patreon to support independent content creators and start reading latest guides:
    • How to set up Redis sentinel cluster on Ubuntu or Debian Linux
    • How To Set Up SSH Keys With YubiKey as two-factor authentication (U2F/FIDO2)
    • How to set up Mariadb Galera cluster on Ubuntu or Debian Linux
    • A podman tutorial for beginners – part I (run Linux containers without Docker and in daemonless mode)
    • How to protect Linux against rogue USB devices using USBGuard

Join Patreon

Set JAVA_HOME / PATH for all user

You need to setup global config in /etc/profile OR /etc/bash.bashrc file for all users:
# vi /etc/profile
Next setup PATH / JAVA_PATH variables as follows:
export PATH=$PATH:/usr/java/jdk1.5.0_07/bin
export PATH=$PATH:/usr/java/jdk1.5.0_07/bin

Save and close the file. Once again you need to type the following command to activate the path settings immediately:
# source /etc/profile
OR
# . /etc/profile

🐧 Get the latest tutorials on Linux, Open Source & DevOps via

Category List of Unix and Linux commands
Documentation help • mandb • man • pinfo
Disk space analyzers df • duf • ncdu • pydf
File Management cat • cp • less • mkdir • more • tree
Firewall Alpine Awall • CentOS 8 • OpenSUSE • RHEL 8 • Ubuntu 16.04 • Ubuntu 18.04 • Ubuntu 20.04
Linux Desktop Apps Skype • Spotify • VLC 3
Modern utilities bat • exa
Network Utilities NetHogs • dig • host • ip • nmap
OpenVPN CentOS 7 • CentOS 8 • Debian 10 • Debian 8/9 • Ubuntu 18.04 • Ubuntu 20.04
Package Manager apk • apt
Processes Management bg • chroot • cron • disown • fg • glances • gtop • jobs • killall • kill • pidof • pstree • pwdx • time • vtop
Searching ag • grep • whereis • which
Shell builtins compgen • echo • printf
Text processing cut • rev
User Information groups • id • lastcomm • last • lid/libuser-lid • logname • members • users • whoami • who • w
WireGuard VPN Alpine • CentOS 8 • Debian 10 • Firewall • Ubuntu 20.04

Comments on this entry are closed.

I believe this is wrong !

1) In my case I did all you said for .bash_profile, however, running which java still shows old java path (crappy java that comes with linux fedora 7)

2) I tried the same to set /etc/profile but I believe you provided wrong sintax

Could somebody provide correct sintax for seting java path in /etc/profile or whatever as long as my which java will show my newest java?

The correct syntax is as show below,

I have read lots of user posting at various pages and none of them would work. Finally, I found a way to do this correctly and hope this will help to some of you.

Follow the simple steps:

1. To set the environment variables :

echo ‘export JAVA_HOME=/opt/jdk1.5.0_12’ > /etc/profile.d/jdk.sh
echo ‘export PATH=$JAVA_HOME/bin:$PATH’ >> /etc/profile.d/jdk.sh

2. You have to source the file you just created by typing:
source /etc/profile.d/jdk.sh

3. Test if Java environment is successfully installed by typing in this in the shell:
java -version

when I type these above script or command my terminal say “Permission denied”.
Tell the answer
Thanks in Advnace

use “sudo ” if you’re using ubuntu.
else try using “su”
Try googling in case both don’t work 😀

Thank you for solution. This worked perfectly for me in Linux.

Thank you. This worked. Nothing else did!

Thanks .
That’s work for me and after testing the version it shows the new version. The other answers couldn’t work for me 🙁

Thank you for this answer, it worked for me. Best regards, Kevin

I have read lots of posting and none of them worked well. This one did so I decided to try to post it hopefully somebody else wont have to get this frustrated to get such a simple thing done.

1. To set the environment variables:

echo ‘export JAVA_HOME=/opt/jdk1.5.0_12’ > /etc/profile.d/jdk.sh
echo ‘export PATH=$JAVA_HOME/bin:$PATH’ >> /etc/profile.d/jdk.sh

2. You have to source the file you just created by typing:
source /etc/profile.d/jdk.sh

3. Test if Java environment is successfully installed by typing in this in the shell:
$ java -version
java version “1.6.0_03”
Java(TM) SE Runtime Environment (build 1.6.0_03-b05)
Java HotSpot(TM) Server VM (build 1.6.0_03-b05, mixed mode)

You can also use which java to test:
$ which java
/usr/java/jdk1.6.0_03/bin/java

hay it is working…but how can i set permentally set…the java path
its working only one terminoal only…
i need permentally java path setting
help me

Setting java class path in Linux:
I have faced the same problem . How to set it permanently. please help me

review of these lines:
……
1. To set the environment variables:

2. You have to source the file you just created by typing:

I have the same problem, something at the startup doesn´t work well in /etc/profile from the /etc/profile.d/*.sh are called.

To resolve this, put the exports directly at the end of the /etc/profile file..
and you have permanently set them, JAVA_HOME and JRE_HOME

+1 Made my day. Thank you.

Thank you, worked for me.

my last reply is using mistakenly 2 different versions of jdk. Reference to jdk in point 1 and 3 should be the same as well as in the testing part

My last 2 postings use 2 different jdk by accident. References to jdk should be the same.

For the sake of consistance, please use (of course substitute your java directory in place of mine /usr/lib/java/jdk….):
echo ‘export JAVA_HOME=/usr/lib/java/jdk1.6.0_03′ > /etc/profile.d/jdk.sh
istead of
echo ‘export JAVA_HOME=/opt/jdk1.5.0_12′ > /etc/profile.d/jdk.sh

at the terminal. You type 2 comand to apply the env for bath shell.
#source /etc/profile
#/etc/init.d/x11-common restart

bas se nesto gnjavim sa serverom ali ovaj tvoj post je dosao k’o kec na desetku.

Thanks for your post, it does exactly what it says on the tin. Just what I needed.

I use the IDE 6 with netbeans to create a simple application and I build it and when I navigate to its dist location through the terminal and type:
>> java -jar addition.jar
it gives me this message could you please help me to solve this problem:
Exception in thread “main” java.lang.NoClassDefFoundError: javax/swing/GroupLayout$Group

i need to run my application with jdk,jmf and jakarta tomcat hw do i go about setting the environment variables?

I think it’s worth mentioning that on most Linux systems, there is a convenient facility to manage different java implementations – its called “alternatives” – depending on the version of your system it may be:
/usr/sbin/alternatives –config java
or
sudo update-alternatives –config java

Rather than log out and back in you can run your new bash profile with a single period:
$ cd
$ . .bash_profile

How to install JDK (Java Development Kit) on Linux, In my case Fedora 10?

1. Log in as root:
su-
type in your password and the prompt will change from $: to #:

2. Download JDK from here:
http://java.sun.com/javase/downloads/index.jsp
As of time of this post, the most current JDK was:
Java SE Development Kit (JDK) 6 Update 11.
Select file jdk-6u11-linux-i586.rpm.bin to download it by providing your operation system and multilanguage.

3. Go to directory where you downloaded the file (In my case it is Download directory in /home/username/Download/)
The file is called jdk-6u11-linux-i586.rpm.bin

4. Change mode of this file so you can execute it by issuing:
chmod 755 jdk-6u11-linux-i586.rpm.bin

5. run the file by issuing:
./jdk-6u11-linux-i586.rpm.bin
This will show acceptance agreement, press untill you reach end they type “yes” and press and the installation will start.

6. When installation completes, you will need to find the actuall location of your JDK and make Fedora accept your choice. You can do this by issuing:
updatedb;locate javac |grep bin

This will list several options (at least two, the default one shipped with fedora, and the one you downloaded from Java Sun in step 2 above. In my case, I get:
[root@DRACHE Download]# locate javac |grep bin
/usr/bin/javac
/usr/java/jdk1.6.0_10/bin/javac
/usr/java/jdk1.6.0_11/bin/javac –this is what we downloaded in step 2 above, we want to make make Fedora recognaze this jdk.

7. To make Fedora recognaze your jdk (JVM), use alternatives command and issue following 3 commands one after another:
alternatives —install /usr/bin/java java /usr/java/jdk1.6.0_11/bin/java 100
alternatives —install /usr/bin/jar jar /usr/java/jdk1.6.0_11/bin/jar 100
alternatives —install /usr/bin/javac javac /usr/java/jdk1.6.0_11/bin/javac 100

These 3 commands set your java, jar and javac commands. You can use same to set other java executables if you want.

8. Configure alternatives to use the jdk you downloaded above in step 2 rather than the java shipped with Fedora by issuing:
/usr/sbin/alternatives —config java

This will present you with at least 2 options (one is the default jdk shipped with Fedora, other is jdk you downloaded in step 2 above). In my case, I have somehting like this but in your case, this can look different:
/usr/sbin/alternatives —config java

There are 6 programs which provide ‘java’.

Enter to keep the current selection[+], or type selection number:

9. Choose the one you downloaded in step 2 above and press . In my case, that is option 4.

10. repeat the same for jar and javac command as:
/usr/sbin/alternatives —config jar
/usr/sbin/alternatives —config javac

11. Issue:
java -version
and you will see something like this:

[dino@DRACHE Download]$ java -version
java version “1.6.0_11”
Java(TM) SE Runtime Environment (build 1.6.0_11-b03)
Java HotSpot(TM) Server VM (build 11.0-b16, mixed mode)

Now you are done. Hope this helps 🙂
Mustafa Buljubasic

Thanks to article from Angsuman Chakraborty from August 7th, 2007

Thanks Mustafa, It worked like a charm for me , am using RHEL5

Источник

Читайте также:  Windows не удается найти documents
Оцените статью