Get java jdk path

Как найти, где JDK установлен на моем компьютере Windows?

При запуске Java -version в cmd он отображает версию как «1.6.xx». Чтобы найти местоположение этого SDK на моем компьютере, я попытался использовать echo %JAVA_HOME% , но он показывает только «JAVA_HOME» (так как в переменных среды нет JAVA_PATH).

ОТВЕТЫ

Ответ 1

Если вы используете Linux/Unix/Mac OS X:

Должно вывести точное местоположение.

После этого вы можете сами установить переменную среды JAVA_HOME .

В моем компьютере (Mac OS X — Snow Leopard):

$ which java /usr/bin/java $ ls -l /usr/bin/java lrwxr-xr-x 1 root wheel 74 Nov 7 07:59 /usr/bin/java -> /System/Library/Frameworks/JavaVM.framework/Versions/Current/Commands/java 

Если вы используете Windows:

c:\> for %i in (java.exe) do @echo. %~$PATH:i 

Ответ 2

C:> for %i in (javac.exe) do @echo. %~$PATH:i 

Если у вас установлен JDK, отображается Путь,
например: C:\Program Files\Java\jdk1.6.0_30\bin\javac.exe

Ответ 3

В Windows в командной строке

Ответ 4

Установщик Java помещает несколько файлов в папку% WinDir%\System32 (java.exe, javaws.exe и некоторые другие). Когда вы вводите java.exe в командной строке или создаете процесс без полного пути, Windows запускает их как последнее средство, если они отсутствуют в папках% PATH%.

Вы можете найти все версии Java, установленные в реестре. Взгляните на HKLM\SOFTWARE\JavaSoft\Java Runtime Environment и HKLM\SOFTWARE\Wow6432Node\JavaSoft\Java Runtime Environment для 32-разрядной Java на 64-битной Windows.

Вот как сама Java обнаруживает разные версии. И поэтому и 32-битная, и 64-битная версия могут сосуществовать и прекрасно работать, не мешая.

Ответ 5

В окнах по умолчанию: C:\Program Files\Java\jdk1.6.0_14 (где числа могут отличаться, поскольку они являются версией).

Ответ 6

Обычная и простая на платформах Windows:

Ответ 7

Пакет script ниже распечатает существующую стандартную JRE. Его можно легко изменить, чтобы найти версию JDK, установленную путем замены Java Runtime Environment Java Development Kit.

@echo off setlocal ::- Get the Java Version set KEY="HKLM\SOFTWARE\JavaSoft\Java Runtime Environment" set VALUE=CurrentVersion reg query %KEY% /v %VALUE% 2>nul || ( echo JRE not installed exit /b 1 ) set JRE_VERSION= for /f "tokens=2,*" %%a in ('reg query %KEY% /v %VALUE% ^| findstr %VALUE%') do ( set JRE_VERSION=%%b ) echo JRE VERSION: %JRE_VERSION% ::- Get the JavaHome set KEY="HKLM\SOFTWARE\JavaSoft\Java Runtime Environment\%JRE_VERSION%" set VALUE=JavaHome reg query %KEY% /v %VALUE% 2>nul || ( echo JavaHome not installed exit /b 1 ) set JAVAHOME= for /f "tokens=2,*" %%a in ('reg query %KEY% /v %VALUE% ^| findstr %VALUE%') do ( set JAVAHOME=%%b ) echo JavaHome: %JAVAHOME% endlocal 

Ответ 8

Подробнее о Windows. переменная java.home не всегда совпадает с местом запуска исполняемого бина.

Как говорит Denis The Menace, установщик помещает файлы Java в Program Files, а также java.exe в System32. Ничего не связано с Java на пути java -version. Однако, когда программа PeterMmm запущена, она сообщает значение Program Files как java.home, это не так (Java там установлен), но фактический исполняемый файл находится в System32.

Один из способов поиска местоположения двоичного файла java.exe, добавьте следующую строку в код PeterMmm, чтобы программа продолжалась дольше:

Скомпилируйте и запустите его, затем найдите местоположение изображения java.exe. Например. в Windows 7 откройте диспетчер задач, найдите запись java.exe, щелкните правой кнопкой мыши и выберите «открыть местоположение файла», это откроет точное местоположение двоичного файла Java. В этом случае это будет System32.

Ответ 9

В командной строке Windows просто введите:

Или, если вам не нравится командная среда, вы можете проверить ее:

Меню «Пуск» > «Компьютер» > «Свойства системы» > «Дополнительные свойства системы». Затем откройте вкладку «Дополнительно» > «Переменные среды» и в системной переменной попытайтесь найти JAVA_HOME.

enter image description here

Ответ 10

Запустите эту программу из командной строки:

// File: Main.java public class Main < public static void main(String[] args) < System.out.println(System.getProperty("java.home")); >> $ javac Main.java $ java Main 

Ответ 11

В Windows вы можете использовать

чтобы напечатать полный путь каждого «java.exe» на вашем диске C:, независимо от того, находятся ли они в вашей переменной среды PATH.

Ответ 12

Пробовали ли вы просматривать%% PATH%. Это то, что Windows использует для поиска любого исполняемого файла.

Ответ 13

Просто выполните команду set в командной строке. Затем вы увидите все переменные окружения, которые вы установили.

Или если в Unix вы можете упростить его:

Ответ 14

отобразит путь к исполняемому файлу. Я не знаю эквивалента Windows, но там обычно есть папка bin для установки JDK в системе PATH :

Ответ 15

Ни один из этих ответов не подходит для Linux, если вы ищете дом, который включает в себя поддиры, такие как: bin, docs, include, jre, lib и т.д.

В Ubuntu для openjdk1.8.0 это находится в: /usr/lib/jvm/java-1.8.0-openjdk-amd64

и вы можете использовать его для JAVA_HOME , так как вы сможете находить заголовки, если вы создадите исходные файлы JNI. Хотя true which java предоставит двоичный путь, это не настоящий JDK home.

Ответ 16

$p='HKLM:\SOFTWARE\JavaSoft\Java Development Kit'; $v=(gp $p).CurrentVersion; (gp $p/$v).JavaHome 

Ответ 17

В Windows 10 вы можете узнать путь, выбрав «Панель управления» > «Java». На панели, которая отображается, вы можете найти путь, как показано на скриншоте ниже. В панели управления Java перейдите на вкладку «Java», а затем нажмите кнопку «Просмотр» в разделе «Просмотр и управление версиями и настройками Java Runtime для приложений и апплетов Java».

Это должно работать на Windows 7 и, возможно, на других последних версиях Windows.

введите описание изображения здесь

Ответ 18

#!/bin/bash if [[ $(which $/bin/java) ]]; then exe="$/bin/java" elif [[ $(which java) ]]; then exe="java" else echo "Java environment is not detected." exit 1 fi $ -version 
@echo off if "%JAVA_HOME%" == "" goto nojavahome echo Using JAVA_HOME : %JAVA_HOME% "%JAVA_HOME%/bin/java.exe" -version goto exit :nojavahome echo The JAVA_HOME environment variable is not defined correctly echo This environment variable is needed to run this program. goto exit :exit 

Эта ссылка может помочь объяснить, как найти исполняемый файл java из bash: http://srcode.org/2014/05/07/detect-java-executable/

Ответ 19

Источник

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.

Источник

How to find path to java?

That tells the command java resides in /usr/bin/java.

$ ls -l /usr/bin/java lrwxrwxrwx 1 root root 22 2009-01-15 18:34 /usr/bin/java -> /etc/alternatives/java 

So, now we know that /usr/bin/java is actually a symbolic link to /etc/alternatives/java .

Dig deeper using the same method above:

$ ls -l /etc/alternatives/java lrwxrwxrwx 1 root root 31 2009-01-15 18:34 /etc/alternatives/java -> /usr/local/jre1.6.0_07/bin/java 

So, thats the actual location of java: /usr/local/jre.

You could still dig deeper to find other symbolic links.

export JAVA_HOME=$(dirname $(dirname $(update-alternatives --list javac))) 

To make this seemingly over done setting clearer, on my Ubuntu linux machine with open JDK 8 installed:

$ update-alternatives --list java /usr/lib/jvm/java-8-openjdk-amd64/jre/bin/java $ update-alternatives --list javac /usr/lib/jvm/java-8-openjdk-amd64/bin/javac 

but what we need is the path to the directory containing bin of the JDK. So ask for the location of javac and then use dirname twice.

See man update-alternatives for more.

Be aware of the possibility that people might have two JDK’s installed. To always use the first one as your JAVA_HOME you can use head : JAVA_HOME=$(dirname $(dirname $(update-alternatives —list javac 2>&1 | head -n 1)))

Starting from January 2019, the licensing model for Oracle Java has changed. PPAs such as ‘ppa:webupd8team/java’ used in many Java installation tutorials now become unavailable.

Here I would like to share how I installed Java 8 on Ubuntu 16.04, and set the Java path in terminal.

Installation

I followed the instruction on the official documentation to install Java with .tar.gz

Path setting

The instruction is also from the official documentations. The steps to set up Java path are much simpler here.

After performing all the steps, restart the terminal and run ‘java -version’ to verify installation.

Источник

Читайте также:  Java how to copy list
Оцените статью