Linux get java home

A system-wide way to set or get $JAVA_HOME in Ubuntu?

A little hacky, but put this line in your /etc/profile for setting it system-wide:

export JAVA_HOME=$(dirname $(dirname $(readlink -e /usr/bin/javac))) 

Some sysadmins like to fiddle with the PATH so the /usr/bin isn’t necessarily the first place looked. To be sure you are picking up the path of the version you will actually run, a better re-hack may be: export JAVA_HOME=$(dirname $(dirname $(readlink -e $(which javac))))

You can set environment variables in /etc/environment , which gets setup by PAM. There should also be symlinks in /usr/lib/jvm which don’t change with minor releases.

JAVA_HOME=/usr/lib/jvm/java-6-sun 

If you’re sure the ‘java’ command can be called, wouldn’t this work for you?

export JAVA_HOME=$(dirname $(java -XshowSettings:properties -version 2>&1 | grep 'java\.home' | awk '< print $3 >')) 

The accepted solution byuser13742 assumes that the server definitely has Java installed. In case you’re adding this to a centralized script for many servers it will give some errors like:

dirname: missing operand Try 'dirname --help' for more information. 

To avoid that and only set JAVA_HOME if the server has a Java environment, a slight enhancement is:

if [ -f "$(which javac)" ]; then export JAVA_HOME=$(dirname $(dirname $(readlink -e $(which javac)))) fi 

I also incorporated the change from SimonB to use which to find where the installation is.

Читайте также:  Unlimited java cryptography extensions

Источник

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.

Источник

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

Узнайте, что существует несколько способов найти 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.

Читайте ещё по теме:

Источник

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