- How to find path where jdk installed?
- 4 Answers 4
- JAVA_HOME directory in Linux
- 11 Answers 11
- Как найти JAVA_HOME
- 1. введение
- 2. Специфичные для Windows способы поиска JAVA_HOME
- 3. Специфичные для macOS и Linux способы поиска JAVA_HOME
- 4. Использование Java для поиска JAVA_HOME
- 5. Заключение
- Читайте ещё по теме:
- How to find my current JAVA_HOME in ubuntu?
How to find path where jdk installed?
I’ve installed jdk1.7.0.rpm package in RHEL6.
Where I do find the path to execute my first java program?
Hi, Mohammad. It’s not a stupid question, but one that has been answered in several places already — like this or this question.
Just an PS: on MacOS, Java is usually installed at ‘/System/Library/Java/JavaVirtualMachines/1.6.0.jdk/Contents/Home’, where the version number could be different.
4 Answers 4
For your first java program read this tutorial:
Note these commands give different results. If you are interested in the non-symlink path use whereis java.
I don’t really think this answers the question. The java binary gets installed with the JRE, but if you’re doing development you need JDK, which isn’t necessarily installed in which java (which in my case is /usr/bin).
On RHEL7, you can use locate :
and it led me to the /usr/lib/jvm/ directory which contained the directories:
java-1.8.0-openjdk-1.8.0.161-0.b14.el7_4.x86_64/ jre/ jre-1.8.0/ jre-1.8.0-openjdk/ jre-1.8.0-openjdk-1.8.0.161-0.b14.el7_4.x86_64/ jre-openjdk/
Each of these contain a bin/java
To find the full path of the symbolic link use:
This gave me mostly JDK6 even though java -version gave me 1.8. There was one link to the JDK8 folder near the top.
You can list the installed files with
You will see somewhere a bin directory with java executable
But if the JDK RPM was correctly installed you should already find java in you path.
javac MyFirstJavaClass.java
and if everything compiles
(If you didn’t change anything the current directory . should already be in your class path)
Since this question is RPM specific, rpm is the way to get started (as answered by @Matteo).
-q is short for --query -l is short for --list
rpm -ql jdk1.8.0_20 | grep "jdk1.8.0_20/bin$"
Knowing this may be desirable for setting a user or application’s $JAVA_HOME variable. This is often needed when a system has multiple versions of java installed, or multiple distributions of java installed, such as OpenJDK and Oracle/Sun.
$JAVA_HOME Example
In the ~/.bash_profile , or related file ( .bashrc , .zshrc , .cshrc , setenv.sh ), something similar to the below may be used.
JAVA_HOME='/usr/java/jdk1.8.0_20' export JAVA_HOME PATH="$JAVA_HOME/bin:$PATH" export PATH
If you would like more control over where Java gets installed, such as in /opt , then the tarball can be used instead of the RPM file.
Other similar questions, are asking about how to find any binary or file, in the general case.
JAVA_HOME directory in Linux
Is there any linux command I could use to find out JAVA_HOME directory? I’ve tried print out the environment variables («env») but I can’t find the directory.
11 Answers 11
On Linux you can run $(dirname $(dirname $(readlink -f $(which javac))))
On Mac you can run $(dirname $(readlink $(which javac)))/java_home
I’m not sure about windows but I imagine where javac would get you pretty close
This is a great solution, but remember to use the canonical flag for readlink as Java can be set up with multiple links, so use $(dirname $(dirname $(readlink -f $(which javac)))) on Linux instead
Thanks @MatthewO’Riordan! I added the -f flag for the linux command. Note that readlink on mac is not the GNU version so I excluded -f for the mac version of the script. Mac users that have the GNU version of readlink installed via brew can use -f .
This is the best solution to find any home paths. I use it frequently for java, maven, and whatnot! Thank you!
Ah, nevermind, the intention is clearer with an echo before it: echo $(dirname $(dirname $(readlink -f $(which javac))))
Just another solution, this one’s cross platform (uses java ), and points you to the location of the jre.
java -XshowSettings:properties -version 2>&1 > /dev/null | grep 'java.home'
Outputs all of java ‘s current settings, and finds the one called java.home .
For windows, you can go with findstr instead of grep.
java -XshowSettings:properties -version 2>&1 | findstr "java.home"
I’ve reseached a lot of ways to find JAVA_HOME and I think this is one of the best! Thanks for mentioning it!
It’s probably worth mentioning that this started working with JDK1.7 (IIRC). Before that you would have needed to call: jrunscript -e ‘java.lang.System.out.println(java.lang.System.getProperty(«java.home»));’ . In both cases, for ‘cross-platform’ aspects, it is recommendable to prepend a /usr/bin/env .
echo $JAVA_HOME will print the value if it’s set. However, if you didn’t set it manually in your startup scripts, it probably isn’t set.
If you try which java and it doesn’t find anything, Java may not be installed on your machine, or at least isn’t in your path. Depending on which Linux distribution you have and whether or not you have root access, you can go to http://www.java.com to download the version you need. Then, you can set JAVA_HOME to point to this directory. Remember, that this is just a convention and shouldn’t be used to determine if java is installed or not.
@harschware When I install Ubuntu the JAVA_HOME is not set, even with the JDK installed. Also read /usr/share/doc/openjdk-8-jre-headless/JAVA_HOME and it says the JAVA_HOME should no longer be needed (legacy).
@PeterQuiring Thanks Peter, unfortunately I don’t have easy access to that file. Perhaps there is an effort to deprecate it in Java 8, but the shear number of tools that rely on JAVA_HOME will mandate a need to continue to define the variable for many years yet.
I know this is late, but this command searches the /usr/ directory to find java for you
/usr/lib/jvm/java-6-openjdk /usr/lib/jvm/java-1.6.0-openjdk
FYI, if you are on a Mac, currently JAVA_HOME is located at
You might want to try sudo find /usr/ -name *jdk* as my path was /usr/lib/jvm/java-7-openjdk-amd64/ .
To show the value of an environment variable you use:
In case you don’t have it setted, you can add in your .bashrc file:
export JAVA_HOME=$(readlink -f /usr/bin/java | sed «s:bin/java::»)
and it will dynamically change when you update your packages.
Unsafe sed command: what if /usr/bin/java was a symlink to /usr/bin/java-8/bin/java ? You’d get the output /usr/-8/bin/java .
Fantastic Solution! if you want to use jdk as home instead of jre just tweak readlink -f /usr/bin/java | sed «s:jre/bin/java::»
If $JAVA_HOME is defined in your environment.
$ echo $JAVA_HOME $ # I am not lucky.
You can guess it from the classes that are loaded.
$ java -showversion -verbose 2>&1 | head -1 [Opened /usr/lib/jvm/java-1.7.0-openjdk-1.7.0.75.x86_64/jre/lib/rt.jar]
This method ensures you find the correct jdk / jre used in case there are multiple installations.
$ strace -e open java -showversion 2>&1 | grep -m1 /jre/ open("/usr/lib/jvm/java-1.7.0-openjdk-1.7.0.75.x86_64/jre/bin/../lib/amd64/jli/tls/x86_64/libpthread.so.0", O_RDONLY) = -1 ENOENT (No such file or directory)
If you are not getting anything, then your environment variable JAVA_HOME has not been set. You can try using «locate java» to try and discover where your installation of Java is located.
Did you set your JAVA_HOME
- Korn and bash shells:export JAVA_HOME=jdk-install-dir
- Bourne shell:JAVA_HOME=jdk-install-dir;export JAVA_HOME
- C shell:setenv JAVA_HOME jdk-install-dir
Here’s an improvement, grabbing just the directory to stdout:
java -XshowSettings:properties -version 2>&1 \ | sed '/^[[:space:]]*java\.home/!d;s/^[[:space:]]*java\.home[[:space:]]*=[[:space:]]*//'
A bit shorter, though with three forks instead of two, is the following: : $
If one needs to export the path directly: export $(/usr/bin/env java -XshowSettings:properties -version 2>&1 | grep «java.home» | sed -e ‘s/java.home/JAVA_HOME/;s/ //g;’)
You can check from the command line by executing this command echo $JAVA_HOME . If Java is installed but the path is not set, you need to identify the path to your java installation. I prefer using sudo update-alternatives —config java which lists all installed versions with current active one marked and provides dialog to switch:
There are 3 programs which provide 'java'. Selection Command ----------------------------------------------- 1 java-11-openjdk.x86_64 (/usr/lib/jvm/java-11-openjdk-11.0.14.0.9-2.fc35.x86_64/bin/java) 2 java-17-openjdk.x86_64 (/usr/lib/jvm/java-17-openjdk-17.0.2.0.8-1.fc35.x86_64/bin/java) *+ 3 /usr/java/jdk-17.0.2/bin/java Enter to keep the current selection[+], or type selection number:
from the above list, you can select the version of java you want to be the default. To set the JAVA_HOME to option 3 for instance you can do it this way export JAVA_HOME=/usr/java/jdk-17.0.2
Как найти JAVA_HOME
Узнайте, что существует несколько способов найти JAVA_HOME, в том числе независимый от платформы.
1. введение
В этом кратком посте мы узнаем, как найти JAVA_HOME в Windows, Mac и Linux.
Как мы все знаем, JAVA_HOME – это переменная среды, которую мы обычно используем для поиска исполняемых файлов java, таких как java и javac .
2. Специфичные для Windows способы поиска JAVA_HOME
Если мы используем Windows в качестве операционной системы, сначала нам нужно открыть нашу командную строку ( cmd ) и ввести:
Если JAVA_HOME определен в нашей среде, то приведенная выше команда распечатает его.
Или мы могли бы попробовать:
Который покажет местоположение исполняемого файла java .
3. Специфичные для macOS и Linux способы поиска JAVA_HOME
Если мы используем macOS или Linux, мы можем открыть наш терминал и ввести:
Если JAVA_HOME определен в нашей среде, то приведенная выше команда распечатает его.
Или мы могли бы попробовать:
Что, вероятно, просто показывает нам /usr/bin/java.
Но на самом деле это не очень полезно, так как это символическая ссылка. Чтобы разгадать это, мы будем использовать dirname и readlink ;
dirname $(dirname $(readlink -f $(which javac)))
$(dirname $(readlink $(which javac)))/java_home
В результате эта команда выводит используемую в данный момент папку java.
4. Использование Java для поиска JAVA_HOME
И, если мы можем запустить java сами, то у нас тоже есть почти независимый от платформы способ:
java -XshowSettings:properties -version
Выполнение этой команды выводит множество свойств, одним из которых является java.home.
Однако для его анализа нам все равно понадобится инструмент для конкретной платформы.
Для Linux и macOS , давайте использовать grep :
java -XshowSettings:properties -version 2>&1 > /dev/null | grep 'java.home'
А для Windows давайте использовать findstr :
java -XshowSettings:properties -version 2>&1 | findstr "java.home"
5. Заключение
С помощью этого быстрого сообщения мы узнали, как найти JAVA_HOME в разных операционных системах.
Если они не сработали, возможно, мы неправильно установили переменную JAVA_HOME при установке Java.
Читайте ещё по теме:
How to find my current JAVA_HOME in ubuntu?
To display JAVA_HOME variable path, type in terminal:
If nothing appears then set it with this:
export JAVA_HOME=/usr/lib/jvm/java-7-openjdk-amd64
This will differ according to your JDK type and version.
For displaying it again, follow the first command.
Follow JREs from different vendors on the same system, for using different JDK’s or switch between JDK’s.
It gives «/usr/lib/jvm/java-6-sun». But I have installed java 7. When I check it using «java -version» it gives java version «1.7.0_45» Java(TM) SE Runtime Environment (build 1.7.0_45-b18) Java HotSpot(TM) Server VM (build 24.45-b08, mixed mode)
then execute second command for setting JAVA_HOME variable. NOTE: JAVA_HOME doesn’t make jdk default, it just makes JAVA_HOME variable set to a path & if you want to use different jdk installed on same machine then check my answer, I have edited it.
@Jax-L But now when I give echo JAVA_HOME it just displays as «JAVA_HOME». The path I gave is not displaying.
export works only until you restart. Or you add export to the .bashrc login script. But the correct way to set such environment variables is in /etc/environment
If you have JDK 1.6 (corresponding to Java 6) or a newer version installed, you should have a program named jrunscript in your PATH . You can use this to find the corresponding JAVA_HOME . Example:
$ jrunscript -e 'java.lang.System.out.println(java.lang.System.getProperty("java.home"));' /opt/local/jdk1.7.0_76/jre
You could set the environment variable like this:
$ export JAVA_HOME="$(jrunscript -e 'java.lang.System.out.println(java.lang.System.getProperty("java.home"));')"
Note that the JRE doesn’t include jrunscript , so this will only work if you install the JDK, not just the JRE.