I am trying get the latest JRE installed in windows using dir command. I Have JRE 1.6 and 1.8 installed on my Windows but I need to get whatever the latest version installed in windows (even in future it may change to 1.8 to 2.0*). Can any one please help on this.
Try this batch for win7
#echo off
#echo off
rem http://technet.microsoft.com/en-us/library/bb490890.aspx
SETLOCAL EnableDelayedExpansion
:: findJDK.bat
rem start:-> Run a command in a separate process, or run a file with its default associated application
rem REGEDIT.EXE: -> Export to a (.REG) file:
rem REGEDIT.EXE [ /L:system | /R:user ] /E exportfile.REG "registry_key"
start /w regedit /e reg1.txt "HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\JavaSoft\Java Development Kit"
rem TYPE: -> Display text file content in console
rem FIND: -> Search files or standard output
rem reserved key words regarding reg-key -> "JavaHome" "MicroVersion" "RuntimeLib"
rem | Reads the output from one command and writes it to the input of another command. Also known as a pipe.
type reg1.txt | find "JavaHome" > reg2.txt
if errorlevel 1 goto ERROR
for /f "tokens=2 delims==" %%x in (reg2.txt) do (
set JavaTemp=%%~x
echo Regedit: JAVA_HOME path : !JavaTemp!
)
if errorlevel 1 goto ERROR
echo.
set JAVA_HOME=%JavaTemp%
set JAVA_HOME=%JAVA_HOME:\\=\%
echo JAVA_HOME was found to be %JAVA_HOME%
start /w regedit /e reg3.txt "HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\JavaSoft\Java Runtime Environment"
type reg3.txt | find "RuntimeLib" > reg4.txt
if errorlevel 1 goto ERROR
for /f "tokens=2 delims==" %%x in (reg4.txt) do (
set JavaTemp=%%~x
echo Regedit: JRE_HOME path : !JavaTemp!
)
if errorlevel 1 goto ERROR
echo.
set JRE_HOME=%JavaTemp%
set JRE_HOME=%JRE_HOME:\\=\%
echo JRE_HOME was found to be %JRE_HOME%
goto END
:ERROR
echo A reg1.txt is: & type reg1.txt
echo B reg2.txt is: & type reg2.txt
echo
:END
echo END
pause
java -version:1.8.0_101 -jar jarname.jar
Use above way to invoke java here you can give version of java which you want to use in case there are multiple in your path .
In order to use a USB magstripe reader for accepting credit cards on a PC, my company uses Java on our web portal. In order to get the magstripe reader working properly, our Helpdesk has to guide customers through moving rxtxSerial.dll and RXTXcomm.jar files to the respective bin and lib\ext folders in Windows. We also have to add two URLs to the site exceptions list in the Java Control Panel. Both of these processes currently involve using the GUI and guiding our customers through doing this on their computers.
Java isn't really a strong suit for me. I am trying to create a batch file (with the .dll and .jar files in the same directory) that will automate both processes so that all a user has to do is run the batch file. However, I am running into a few problems that I'm not entirely prepared for.
I need to be able to have this file work for all possible installation paths of Java on the customer's computer. I am fine having a separate batch file for 32-but and 64-bit Java. However, not every customer has the jre8 folder in their "C:\Program Files (x86)\Java" directory. Sometimes instead of jre8, they will have something like jre1.8.0_31. I need the batch file to be able to account for these differences as well.
As far as my understanding goes, the sites.exceptions file is stored in a subdirectory contained within the user's directory. The problem is that I need to be able to create a batch file that will be able to locate the current user's directory as a part of the full file path. Furthermore, I'm not entirely clear on how to edit the sites.exceptions from the command prompt. I suppose I could have a pre-made exceptions file that gets copied over the the right directory (and naturally overriding any currently existing file).
I'm very new to the IT field, so I don't know if what I am asking is possible or if I'm explaining this right. I would really appreciate some help.
I think this might help you. This program detects wheter Java is installed or not. It also detects which version of java etc.
#echo off
if "%OS%" == "Windows_NT" setlocal
::::::::::::::::::::::::::::::::::::
:: Set JAVA_HOME or JRE_HOME ::
::::::::::::::::::::::::::::::::::::
set JDKKeyName64=HKEY_LOCAL_MACHINE\SOFTWARE\JavaSoft\Java Development Kit
set JDKKeyName32=HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\JavaSoft\Java Development Kit
set JREKeyName64=HKEY_LOCAL_MACHINE\SOFTWARE\JavaSoft\Java Runtime Environment
set JREKeyName32=HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\JavaSoft\Java Runtime Environment
reg query "%JDKKeyName64%" /s
if %ERRORLEVEL% EQU 1 (
echo .Could not find 32 bit or 64 bit JDK
echo .Looking for 32 bit JDK on 64 bit machine
goto FINDJDK32
)
set KeyName=%JDKKeyName64%
goto JDKRUN
:FINDJDK32
reg query "%JDKKeyName32%" /s
if %ERRORLEVEL% EQU 1 (
echo .Could not find 32 bit JDK
echo .Looking for 32 bit or 64 bit JRE
goto FINDJRE64
)
set KeyName=%JDKKeyName32%
goto JDKRUN
:FINDJRE64
reg query "%JREKeyName64%" /s
if %ERRORLEVEL% EQU 1 (
echo .Could not find 32 bit or 64 bit JRE
echo .Looking for 32 bit JRE on 64 bit machine
goto FINDJRE32
)
set KeyName=%JREKeyName64%
goto JRERUN
:FINDJRE32
reg query "%JREKeyName32%" /s
if %ERRORLEVEL% EQU 1 (
echo .Could not find 32 bit JRE
echo .Could not set JAVA_HOME or JRE_HOME. Aborting
goto ENDERROR
)
set KeyName=%JREKeyName32%
goto JRERUN
:JDKRUN
echo.
echo Using JDK
set "CURRENT_DIR=%cd%"
set "YOUR_PROGRAM_HOME_HERE=%CURRENT_DIR%"
set Cmd=reg query "%KeyName%" /s
for /f "tokens=2*" %%i in ('%Cmd% ^| find "JavaHome"') do set JAVA_HOME=%%j
echo.
echo Seems fine!
echo Set JAVA_HOME : %JAVA_HOME%
echo Set YOUR_PROGRAM_HOME_HERE : %YOUR_PROGRAM_HOME_HERE%
echo.
goto NEXT
:JRERUN
echo.
echo [XAMPP]: Using JRE
set "CURRENT_DIR=%cd%"
set "YOUR_PROGRAM_HOME_HERE=%CURRENT_DIR%\tomcat"
set Cmd=reg query "%KeyName%" /s
for /f "tokens=2*" %%i in ('%Cmd% ^| find "JavaHome"') do set JRE_HOME=%%j
echo.
echo Seems fine!
echo Set JRE_HOME : %JRE_HOME%
echo Set YOUR_PROGRAM_HOME_HERE : %CATALINA_HOME%
echo.
:ENDERROR
exit 1
:NEXT
echo Finding Java Version
set Cmd=reg query "%KeyName%" /v CurrentVersion
for /f "tokens=2*" %%i in ('%Cmd% ^| find "CurrentVersion"') do set CVERSION=%%j
echo Java Version: %CVERSION%
echo Starting Service Install...
echo .
rem ----------END JAVA SEARCH-----------------------------------------------------------------
Now we've found the java HomeDirectory we can execute our packets trough java. We can use java trough cmd, so this should need to be easy.
Example of what we can do now:
rem Make sure prerequisite environment variables are set
if not "%JAVA_HOME%" == "" goto gotJdkHome
if not "%JRE_HOME%" == "" goto gotJreHome
echo Neither the JAVA_HOME nor the JRE_HOME environment variable is defined
echo Service will try to guess them from the registry.
goto runAsUser
:gotJreHome
if not exist "%JRE_HOME%\bin\java.exe" goto noJavaHome
if not exist "%JRE_HOME%\bin\javaw.exe" goto noJavaHome
goto runAsUser
:gotJdkHome
if not exist "%JAVA_HOME%\jre\bin\java.exe" goto noJavaHome
if not exist "%JAVA_HOME%\jre\bin\javaw.exe" goto noJavaHome
if not exist "%JAVA_HOME%\bin\javac.exe" goto noJavaHome
if not "%JRE_HOME%" == "" goto runAsUser
set "JRE_HOME=%JAVA_HOME%\jre"
goto runAsUser
:noJavaHome
echo The JAVA_HOME environment variable is not defined correctly
echo This environment variable is needed to run this program
echo NB: JAVA_HOME should point to a JDK not a JRE
goto end
Here comes the main code that let's you run your java applet/program
:doInstall
rem Install the service
echo Installing the service '%SERVICE_NAME%' ...
echo Using PROGRAM_HOME: "%YOUR_PROGRAM_HOME_HERE%"
echo Using JAVA_HOME: "%JAVA_HOME%"
echo Using JRE_HOME: "%JRE_HOME%"
rem Use the environment variables as an example
rem Each command line option is prefixed with PR_
set "PR_INSTALL=%EXECUTABLE%"
rem Add another jar or java file next to it with a semicolon. (still in the quotes)
set "PR_CLASSPATH=%YOUR_PROGRAM_HOME_HERE%\javawishprogram.jar;%YOUR_PROGRAM_HOME_HERE%\MaybeASecondoneIfYouwant.jar"
rem Set the server jvm from JAVA_HOME
set "PR_JVM=%JRE_HOME%\bin\server\jvm.dll"
rem Here you can go further on the JVM or not, you can map out your options.
if exist "%PR_JVM%" goto foundJvm
rem Set the client jvm from JAVA_HOME
set "PR_JVM=%JRE_HOME%\bin\client\jvm.dll"
if exist "%PR_JVM%" goto foundJvm
set PR_JVM=auto
:foundJvm
echo Using JVM: "%PR_JVM%"
rem Here you're launching the main programme.
"%EXECUTABLE%" //IS//%SERVICE_NAME% --StartClass programJava.startup.Bootstrap --StartParams start --StopParams stop --Startup auto
You can do even more with this. But I'll let it to your imagination.
I borowed this script from CATALINA
This is the full script:
INGORE
#echo off
rem Licensed to the Apache Software Foundation (ASF) under one or more
rem contributor license agreements. See the NOTICE file distributed with
rem this work for additional information regarding copyright ownership.
rem The ASF licenses this file to You under the Apache License, Version 2.0
rem (the "License"); you may not use this file except in compliance with
rem the License. You may obtain a copy of the License at
rem
rem http://www.apache.org/licenses/LICENSE-2.0
rem
rem Unless required by applicable law or agreed to in writing, software
rem distributed under the License is distributed on an "AS IS" BASIS,
rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
rem See the License for the specific language governing permissions and
rem limitations under the License.
if "%OS%" == "Windows_NT" setlocal
rem ---------------------------------------------------------------------------
rem NT Service Install/Uninstall script
rem
rem Options
rem install Install the service using Tomcat7 as service name.
rem Service is installed using default settings.
rem remove Remove the service from the System.
rem
rem name (optional) If the second argument is present it is considered
rem to be new service name
rem
rem $Id: service.bat 1000718 2010-09-24 06:00:00Z mturk $
rem ---------------------------------------------------------------------------
rem ---------XAMPP-------------------------------------------------------------
::::::::::::::::::::::::::::::::::::
:: Set JAVA_HOME or JRE_HOME ::
::::::::::::::::::::::::::::::::::::
echo.
echo [XAMPP]: Searching for JDK or JRE HOME with reg query ...
set JDKKeyName64=HKEY_LOCAL_MACHINE\SOFTWARE\JavaSoft\Java Development Kit
set JDKKeyName32=HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\JavaSoft\Java Development Kit
set JREKeyName64=HKEY_LOCAL_MACHINE\SOFTWARE\JavaSoft\Java Runtime Environment
set JREKeyName32=HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\JavaSoft\Java Runtime Environment
reg query "%JDKKeyName64%" /s
if %ERRORLEVEL% EQU 1 (
echo . [XAMPP]: Could not find 32 bit or 64 bit JDK
echo . [XAMPP]: Looking for 32 bit JDK on 64 bit machine
goto FINDJDK32
)
set KeyName=%JDKKeyName64%
goto JDKRUN
:FINDJDK32
reg query "%JDKKeyName32%" /s
if %ERRORLEVEL% EQU 1 (
echo . [XAMPP]: Could not find 32 bit JDK
echo . [XAMPP]: Looking for 32 bit or 64 bit JRE
goto FINDJRE64
)
set KeyName=%JDKKeyName32%
goto JDKRUN
:FINDJRE64
reg query "%JREKeyName64%" /s
if %ERRORLEVEL% EQU 1 (
echo . [XAMPP]: Could not find 32 bit or 64 bit JRE
echo . [XAMPP]: Looking for 32 bit JRE on 64 bit machine
goto FINDJRE32
)
set KeyName=%JREKeyName64%
goto JRERUN
:FINDJRE32
reg query "%JREKeyName32%" /s
if %ERRORLEVEL% EQU 1 (
echo . [XAMPP]: Could not find 32 bit JRE
echo . [XAMPP]: Could not set JAVA_HOME or JRE_HOME. Aborting
goto ENDERROR
)
set KeyName=%JREKeyName32%
goto JRERUN
:JDKRUN
echo.
echo [XAMPP]: Using JDK
set "CURRENT_DIR=%cd%"
set "CATALINA_HOME=%CURRENT_DIR%\tomcat"
set Cmd=reg query "%KeyName%" /s
for /f "tokens=2*" %%i in ('%Cmd% ^| find "JavaHome"') do set JAVA_HOME=%%j
echo.
echo [XAMPP]: Seems fine!
echo [XAMPP]: Set JAVA_HOME : %JAVA_HOME%
echo [XAMPP]: Set CATALINA_HOME : %CATALINA_HOME%
echo.
goto NEXT
:JRERUN
echo.
echo [XAMPP]: Using JRE
set "CURRENT_DIR=%cd%"
set "CATALINA_HOME=%CURRENT_DIR%\tomcat"
set Cmd=reg query "%KeyName%" /s
for /f "tokens=2*" %%i in ('%Cmd% ^| find "JavaHome"') do set JRE_HOME=%%j
echo.
echo [XAMPP]: Seems fine!
echo [XAMPP]: Set JRE_HOME : %JRE_HOME%
echo [XAMPP]: Set CATALINA_HOME : %CATALINA_HOME%
echo.
:ENDERROR
exit 1
:NEXT
echo [XAMPP]: Finding Java Version
set Cmd=reg query "%KeyName%" /v CurrentVersion
for /f "tokens=2*" %%i in ('%Cmd% ^| find "CurrentVersion"') do set CVERSION=%%j
echo [XAMPP]: Java Version: %CVERSION%
echo [XAMPP]: Starting Tomcat Service Install...
echo .
rem ----------END XAMPP-----------------------------------------------------------------
set "SELF=%~dp0%service.bat"
rem Guess CATALINA_HOME if not defined
set "CURRENT_DIR=%cd%"
if not "%CATALINA_HOME%" == "" goto gotHome
set "CATALINA_HOME=%cd%"
if exist "%CATALINA_HOME%\bin\tomcat7.exe" goto okHome
rem CD to the upper dir
cd ..
set "CATALINA_HOME=%cd%"
:gotHome
if exist "%CATALINA_HOME%\bin\tomcat7.exe" goto okHome
echo The tomcat.exe was not found...
echo The CATALINA_HOME environment variable is not defined correctly.
echo This environment variable is needed to run this program
goto end
:okHome
rem Make sure prerequisite environment variables are set
if not "%JAVA_HOME%" == "" goto gotJdkHome
if not "%JRE_HOME%" == "" goto gotJreHome
echo Neither the JAVA_HOME nor the JRE_HOME environment variable is defined
echo Service will try to guess them from the registry.
goto okJavaHome
:gotJreHome
if not exist "%JRE_HOME%\bin\java.exe" goto noJavaHome
if not exist "%JRE_HOME%\bin\javaw.exe" goto noJavaHome
goto okJavaHome
:gotJdkHome
if not exist "%JAVA_HOME%\jre\bin\java.exe" goto noJavaHome
if not exist "%JAVA_HOME%\jre\bin\javaw.exe" goto noJavaHome
if not exist "%JAVA_HOME%\bin\javac.exe" goto noJavaHome
if not "%JRE_HOME%" == "" goto okJavaHome
set "JRE_HOME=%JAVA_HOME%\jre"
goto okJavaHome
:noJavaHome
echo The JAVA_HOME environment variable is not defined correctly
echo This environment variable is needed to run this program
echo NB: JAVA_HOME should point to a JDK not a JRE
goto end
:okJavaHome
if not "%CATALINA_BASE%" == "" goto gotBase
set "CATALINA_BASE=%CATALINA_HOME%"
:gotBase
set "EXECUTABLE=%CATALINA_HOME%\bin\tomcat7.exe"
rem Set default Service name
set SERVICE_NAME=Tomcat7
set PR_DISPLAYNAME=Apache Tomcat 7
if "x%1x" == "xx" goto displayUsage
set SERVICE_CMD=%1
shift
if "x%1x" == "xx" goto checkServiceCmd
:checkUser
if "x%1x" == "x/userx" goto runAsUser
if "x%1x" == "x--userx" goto runAsUser
set SERVICE_NAME=%1
set PR_DISPLAYNAME=Apache Tomcat %1
shift
if "x%1x" == "xx" goto checkServiceCmd
goto checkUser
:runAsUser
shift
if "x%1x" == "xx" goto displayUsage
set SERVICE_USER=%1
shift
runas /env /savecred /user:%SERVICE_USER% "%COMSPEC% /K \"%SELF%\" %SERVICE_CMD% %SERVICE_NAME%"
goto end
:checkServiceCmd
if /i %SERVICE_CMD% == install goto doInstall
if /i %SERVICE_CMD% == remove goto doRemove
if /i %SERVICE_CMD% == uninstall goto doRemove
echo Unknown parameter "%1"
:displayUsage
echo.
echo Usage: service.bat install/remove [service_name] [/user username]
goto end
:doRemove
rem Remove the service
"%EXECUTABLE%" //DS//%SERVICE_NAME%
if not errorlevel 1 goto removed
echo Failed removing '%SERVICE_NAME%' service
goto end
:removed
echo The service '%SERVICE_NAME%' has been removed
goto end
:doInstall
rem Install the service
echo Installing the service '%SERVICE_NAME%' ...
echo Using CATALINA_HOME: "%CATALINA_HOME%"
echo Using CATALINA_BASE: "%CATALINA_BASE%"
echo Using JAVA_HOME: "%JAVA_HOME%"
echo Using JRE_HOME: "%JRE_HOME%"
rem Use the environment variables as an example
rem Each command line option is prefixed with PR_
set PR_DESCRIPTION=Apache Tomcat 7.0.22 Server - http://tomcat.apache.org/
set "PR_INSTALL=%EXECUTABLE%"
set "PR_LOGPATH=%CATALINA_BASE%\logs"
set "PR_CLASSPATH=%CATALINA_HOME%\bin\bootstrap.jar;%CATALINA_BASE%\bin\tomcat-juli.jar;%CATALINA_HOME%\bin\tomcat-juli.jar"
rem Set the server jvm from JAVA_HOME
set "PR_JVM=%JRE_HOME%\bin\server\jvm.dll"
if exist "%PR_JVM%" goto foundJvm
rem Set the client jvm from JAVA_HOME
set "PR_JVM=%JRE_HOME%\bin\client\jvm.dll"
if exist "%PR_JVM%" goto foundJvm
set PR_JVM=auto
:foundJvm
echo Using JVM: "%PR_JVM%"
"%EXECUTABLE%" //IS//%SERVICE_NAME% --StartClass org.apache.catalina.startup.Bootstrap --StopClass org.apache.catalina.startup.Bootstrap --StartParams start --StopParams stop --Startup auto
if not errorlevel 1 goto installed
echo Failed installing '%SERVICE_NAME%' service
goto ENDERROR
:installed
rem Clear the environment variables. They are not needed any more.
set PR_DISPLAYNAME=
set PR_DESCRIPTION=
set PR_INSTALL=
set PR_LOGPATH=
set PR_CLASSPATH=
set PR_JVM=
rem Set extra parameters
"%EXECUTABLE%" //US//%SERVICE_NAME% --JvmOptions "-Dcatalina.base=%CATALINA_BASE%;-Dcatalina.home=%CATALINA_HOME%;-Djava.endorsed.dirs=%CATALINA_HOME%\endorsed" --StartMode jvm --StopMode jvm
rem More extra parameters
set "PR_LOGPATH=%CATALINA_BASE%\logs"
set PR_STDOUTPUT=auto
set PR_STDERROR=auto
rem XAMPP: We need special parameters for Java 7
if "%CVERSION%" == "1.7" goto JAVA7
:JAVA
"%EXECUTABLE%" //US//%SERVICE_NAME% ++JvmOptions "-Djava.io.tmpdir=%CATALINA_BASE%\temp;-Djava.util.logging.manager=org.apache.juli.ClassLoaderLogManager;-Djava.util.logging.config.file=%CATALINA_BASE%\conf\logging.properties" --JvmMs 128 --JvmMx 256
goto FINISH
:JAVA7
"%EXECUTABLE%" //US//%SERVICE_NAME% ++JvmOptions "-Djava.io.tmpdir=%CATALINA_BASE%\temp;-Djava.util.logging.manager=org.apache.juli.ClassLoaderLogManager;-Djava.util.logging.config.file=%CATALINA_BASE%\conf\logging.properties;-Djava.net.preferIPv4Stack=true" --JvmMs 128 --JvmMx 256
:FINISH
echo The service '%SERVICE_NAME%' has been installed.
:end
cd "%CURRENT_DIR%"
I'm working on few projects and some of them are using different JDK. Switching between JDK versions is not comfortable. So I was wondering if there is any easy way to change it?
I found 2 ways, which should solve this problem, but it doesn't work.
First solution is creating a bat files like this:
#echo off
echo Setting JAVA_HOME
set JAVA_HOME=C:\Program Files\Java\jdk1.7.0_72
echo setting PATH
set PATH=C:\Program Files\Java\jdk1.7.0_72\bin;%PATH%
echo Display java version
java -version
pause
And after running this bat, I see right version of Java. But when I close this CMD and open a new one and type "java -version" it says that I still have 1.8.0_25. So it doesn't work.
Second solution which I found is an application from this site. And it also doesn't work. The same effect as in the first solution.
Any ideas? Because changing JAVA_HOME and PAHT by: Win + Pause -> Advanced System Settings -> Environment Variables -> and editing these variables, is terrible way...
The set command only works for the current terminal. To permanently set a system or user environment variable you can use setx.
setx JAVA_HOME "C:\Program Files\Java\jdk1.7.0_72" /m
The /m option is used to set the variable system wide (and not just for the current user). The terminal must be run as administrator to use this option.
The variable will be available in all new terminal windows, but not the current one. If you also want to use the path in the same window, you need to use both set and setx.
You can avoid manipulating the PATH variable if you just once put %JAVA_HOME% in there, instead of the full JDK path. If you change JAVA_HOME, PATH will be updated too.
There are also a few environment variable editors as alternative to the cumbersome Windows environment variable settings. See "Is there a convenient way to edit PATH in Windows 7?" on Super User.
In case if someone want to switch frequently in each new command window then I am using following approach.
Command Prompt Version:
Create batch file using below code. You can add n number of version using if and else blocks.
#echo off
if "%~1" == "11" (
set "JAVA_HOME=C:\Software\openjdk-11+28_windows-x64_bin\jdk-11"
) else (
set "JAVA_HOME=C:\Program Files\Java\jdk1.8.0_151"
)
set "Path=%JAVA_HOME%\bin;%Path%"
java -version
Save this batch file as SJV.bat and add this file location in your machine's Path environment variable. So now SJV will act as command to "Switch Java Version".
Now open new command window and just type SJV 11 it will switch to Java 11.
Type SJV 8 it will switch to Java 8.
PowerShell Version
Create powershell(ps1) file using below code. You can add n number of version using if and else blocks.
If($args[0] -eq "11")
{
$env:JAVA_HOME = 'C:\Software\openjdk-11+28_windows-x64_bin\jdk-11'
}else{
$env:JAVA_HOME = 'C:\Program Files\Java\jdk1.8.0_151'
}
$env:Path = $env:JAVA_HOME+'\bin;'+$env:Path
java -version
Save this script file as SJV.ps1 and add this file location in your machine's Path environment variable. So now SJV will act as command to "Switch Java Version".
Now open new powershell window and just type SJV 11 it will switch to Java 11.
Type SJV 8 OR SJV it will switch to Java 8.
I hope this help someone who want to change it frequently.
Open Environment Variables editor (File Explorer > right click on
This PC > Properties > Advanced system settings > Environment
Variables...)
Find Path variable in System variables list >
press Edit > put %JAVA_HOME%bin; at first position. This is required
because Java installer adds C:\Program Files (x86)\Common
Files\Oracle\Java\javapath to the PATH which references to the latest Java version installed.
Now you can switch between Java version using setx command (should be run under administrative permissions):
setx /m JAVA_HOME "c:\Program Files\Java\jdk-10.0.1\
(note: there is no double quote at the end of the line and should not be or you'll get c:\Program Files\Java\jdk-10.0.1\" in your JAVA_HOME variable and it breaks your PATH variable)
Solution with system variables (and administrative permissions) is more robust because it puts desired path to Java at the start of the resulting PATH variable.
If your path have less than 1024 characters can execute (Run as Administrator) this script:
#echo off
set "JAVA5_FOLDER=C:\Java\jdk1.5.0_22"
set "JAVA6_FOLDER=C:\Java\jdk1.6.0_45"
set "JAVA7_FOLDER=C:\Java\jdk1.7.0_80"
set "JAVA8_FOLDER=C:\Java\jdk1.8.0_121"
set "JAVA9_FOLDER=C:\Java\jdk-10.0.1"
set "CLEAR_FOLDER=C:\xxxxxx"
(echo "%PATH%" & echo.) | findstr /O . | more +1 | (set /P RESULT= & call exit /B %%RESULT%%)
set /A STRLENGTH=%ERRORLEVEL%
echo path length = %STRLENGTH%
if %STRLENGTH% GTR 1024 goto byebye
echo Old Path: %PATH%
echo ===================
echo Choose new Java Version:
echo [5] JDK5
echo [6] JDK6
echo [7] JDK7
echo [8] JDK8
echo [9] JDK10
echo [x] Exit
:choice
SET /P C=[5,6,7,8,9,x]?
for %%? in (5) do if /I "%C%"=="%%?" goto JDK_L5
for %%? in (6) do if /I "%C%"=="%%?" goto JDK_L6
for %%? in (7) do if /I "%C%"=="%%?" goto JDK_L7
for %%? in (8) do if /I "%C%"=="%%?" goto JDK_L8
for %%? in (9) do if /I "%C%"=="%%?" goto JDK_L9
for %%? in (x) do if /I "%C%"=="%%?" goto byebye
goto choice
#echo on
:JDK_L5
set "NEW_PATH=%JAVA5_FOLDER%"
goto setPath
:JDK_L6
#echo off
set "NEW_PATH=%JAVA6_FOLDER%"
goto setPath
:JDK_L7
#echo off
set "NEW_PATH=%JAVA7_FOLDER%"
goto setPath
:JDK_L8
#echo off
set "NEW_PATH=%JAVA8_FOLDER%"
goto setPath
:JDK_L9
#echo off
set NEW_PATH = %JAVA9_FOLDER%
:setPath
Call Set "PATH=%%PATH:%JAVA5_FOLDER%=%CLEAR_FOLDER%%%"
Call Set "PATH=%%PATH:%JAVA6_FOLDER%=%CLEAR_FOLDER%%%"
Call Set "PATH=%%PATH:%JAVA7_FOLDER%=%CLEAR_FOLDER%%%"
Call Set "PATH=%%PATH:%JAVA8_FOLDER%=%CLEAR_FOLDER%%%"
Call Set "PATH=%%PATH:%JAVA9_FOLDER%=%CLEAR_FOLDER%%%"
rem echo Interim Path: %PATH%
Call Set "PATH=%%PATH:%CLEAR_FOLDER%=%NEW_PATH%%%"
setx PATH "%PATH%" /M
call set "JAVA_HOME=%NEW_PATH%"
setx JAVA_HOME %JAVA_HOME%
echo New Path: %PATH%
:byebye
echo
java -version
pause
If more than 1024, try to remove some unnecessary paths, or can modify this scripts with some inputs from https://superuser.com/questions/387619/overcoming-the-1024-character-limit-with-setx
Run this BAT file to conveniently change the java version.
Pros:
It does NOT modify the PATH system environment variable.
The only thing that has to be maintained is the relational array (can be conveniently constructed as a sparse array) that holds the version number and the path at the beginning of the script.
Precondition:
The following entry %JAVA_HOME%\bin has to be appended to the PATH environment variable.
#echo off
#cls
#title Switch Java Version
setlocal EnableExtensions DisableDelayedExpansion
:: This bat file Switches the Java Version using the JAVA_HOME variable.
:: This script does NOT modify the PATH system environment variable.
:: Precondition: The following entry "%JAVA_HOME%\bin" has to be appended to the PATH environment variable.
:: Script Name: SwitchJavaVersion | Version 1 | 2021/11/04
rem Add items to vector as follows:
rem AvailableVersions["Java Major Version Number"]="Java Absolute Path"
set AvailableVersions[8]="D:\Program Files\Java\jdk8u252-b09"
set AvailableVersions[17]="D:\Program Files\Java\jdk-17.0.1"
call :PrintJavaVersion
call :PrintAvailableVersions
call :GetJavaVersion
call :SetJavaVersion
call :ResetLocalPath
if %errorlevel% neq 0 exit /b %errorlevel%
call :PrintJavaVersion
pause
endlocal
exit /b
rem Print available versions.
:PrintAvailableVersions
echo Available Java Versions:
for /f "tokens=2 delims=[]" %%I in ('set AvailableVersions[') do echo ^> %%I
exit /b
rem Get version from user input or command-line arguments.
:GetJavaVersion
set "JavaVersion="
if "%~1"=="" (
set /p JavaVersion="Type the major java version number you want to switch to: "
) else (
set /a JavaVersion="%~1"
)
exit /b
rem Update JAVA_HOME user variable with hardcoded paths.
:SetJavaVersion
set JavaPath=
for /f "tokens=2 delims=[]" %%I in ('set AvailableVersions[') do (
if "%%I" == "%JavaVersion%" (
setlocal EnableDelayedExpansion
set JavaPath=!AvailableVersions[%%I]!
setlocal EnableExtensions DisableDelayedExpansion
)
)
if not defined JavaPath (
echo "Specified version NOT found: Default settings applied."
for /f "tokens=2 delims==" %%I in ('set AvailableVersions[') do (
set JavaPath=%%I
goto exitForJavaPath
)
)
:exitForJavaPath
rem remove quotes from path
set JavaPath=%JavaPath:"=%
set "JAVA_HOME=%JavaPath%"
setx JAVA_HOME "%JAVA_HOME%"
rem setlocal statement was run 2 times previously inside the for loop; therefore, the endlocal statement must be executed 2 times to close those nested local scopes.
rem below endlocal statement will close local scope set by previous "setlocal EnableExtensions DisableDelayedExpansion" statement
endlocal & set "JavaPath=%JavaPath%"
rem JAVA_HOME's value rolls back due to endlocal statement so the appropriate value has to be reassigned
set "JAVA_HOME=%JavaPath%"
rem below endlocal statement will close local scope set by previous "setlocal EnableDelayedExpansion" statement
endlocal & set "JavaPath=%JavaPath%"
rem JAVA_HOME's value rolls back due to endlocal statement so the appropriate value has to be reassigned
set "JAVA_HOME=%JavaPath%"
exit /b
rem Get User and System Path variable's definition from Registry,
rem evaluate the definitions with the new values and reset
rem the local path variable so newly set java version
rem is properly displayed.
:ResetLocalPath
set "PathValue="
for /F "skip=2 tokens=1,2,*" %%I in ('%SystemRoot%\System32\reg.exe QUERY "HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\Environment" /V Path') do if /I "%%I" == "Path" if not "%%~K" == "" if "%%J" == "REG_SZ" (set "PathValue=%%~K") else if "%%J" == "REG_EXPAND_SZ" call set "PathValue=%%~K"
if not defined PathValue goto pathError
set "UserPathValue="
for /F "skip=2 tokens=1,2,*" %%I in ('%SystemRoot%\System32\reg.exe QUERY "HKCU\Environment" /V Path') do if /I "%%I" == "Path" if not "%%~K" == "" if "%%J" == "REG_SZ" (set "UserPathValue=%%~K") else if "%%J" == "REG_EXPAND_SZ" call set "UserPathValue=%%~K"
if not defined UserPathValue goto pathError
call set "Path=%PathValue%;%UserPathValue%"
echo Path variable reset:
echo PATH=%Path%
echo.
exit /b
rem Display the Java version.
:PrintJavaVersion
echo Current Java Version:
java -version
echo.
exit /b
rem Error handling subroutine.
:pathError
echo.
echo Error while refreshing the PATH variable:
echo PathValue=%PathValue%
echo UserPathValue=%UserPathValue%
pause
exit /b 2
endlocal
exit
Load below mentioned PowerShell script at the start of the PowerShell. or generate the file using New-Item $profile -Type File -Force
this will create a file here C:\Users\{user_name}\Documents\WindowsPowerShell\Microsoft.PowerShell_profile
Now copy-paste the content given below in this file to be loaded each time the PowerShell is started
Set all the java versions you need as separate variables.
Java_8_home-> Points to Java 8 Location in local
Java_11_home -> Points to Java 11 Location in local
Java_17_home -> Points to Java 17 Location in local
Java_Home-> This points to the java version you want to use
Run in power shell to update the version to 8 update_java_version 8 $True
To update execution policy to allow script to be loaded at start of the PowerShell use below command
Set-ExecutionPolicy -Scope CurrentUser -ExecutionPolicy Unrestricted -Force
`
function update_java_version($version, [bool] $everywhere)
{
switch ($version)
{
8 {
$java_value = (Get-Item Env:Java_8_home).value
$Env:Java_Home = $java_value
refresh-path
break
}
11 {
$java_value = (Get-Item Env:Java_11_home).value
$Env:Java_Home = $java_value
refresh-path
break
}
17 {
$java_value = (Get-Item Env:Java_17_home).value
$Env:Java_Home = $java_value
refresh-path
break
}
default {
throw "No matching java version found for `$version`: $version"
}
}
if ($everywhere)
{
[System.Environment]::SetEnvironmentVariable("Java_Home", $java_value, "User")
}
}
function refresh-path
{
$env:Path = [System.Environment]::GetEnvironmentVariable("Path", "Machine") +
";" +
[System.Environment]::GetEnvironmentVariable("Path", "User")
}
Adding to the answer provided here (https://stackoverflow.com/a/64459399/894565).
I manually created environment variables via UI for Java11, Java17 and Java8. To change across Java version:
From powershell (PJV.ps1):
if($args[0] -eq "11") {
$Env:JAVA_HOME="$ENV:JAVA11"
$Env:Path="$Env:JAVA_HOME\bin;$Env:Path"
} elseif($args[0] -eq "17") {
$Env:JAVA_HOME="$ENV:JAVA17"
$Env:Path="$Env:JAVA_HOME\bin;$Env:Path"
} elseif($args[0] -eq "8") {
$Env:JAVA_HOME="$ENV:JAVA8"
$Env:Path="$Env:JAVA_HOME\bin;$Env:Path"
}
set "Path=%JAVA_HOME%\bin;%Path%"
java -version
From command line (JV.bat):
#echo off
if "%~1" == "11" (
set "JAVA_HOME=%JAVA11%"
setx JAVA_HOME "%JAVA11%"
) else if "%~1" == "17" (
set "JAVA_HOME=%JAVA17%"
setx JAVA_HOME "%JAVA17%"
) else (
set "JAVA_HOME=%JAVA8%"
setx JAVA_HOME "%JAVA8%"
)
set "Path=%JAVA_HOME%\bin;%Path%"
java -version
Finally both these files are in the same folder. And this folder path has been added to my system PATH
This question already has answers here:
Get java version from batch file
(5 answers)
Closed 9 years ago.
I need to set JAVA_HOME variable using batch script
Tried below codes, but no use.
for /f %%j in ("java.exe") do #echo.%%~dp$PATH:j
the above script gives empty
FOR /F "skip=2 tokens=2*" %%A IN ('REG QUERY
"HKLM\Software\JavaSoft\Java Runtime Environment" /v CurrentVersion')
DO set CurVer=%%B
the above script gives 1.6
dir java.exe /B /S
the above script gives C:\Windows\System32 but actually java installed in C:\Program Files\Java\jdk1.6.0_31
I need to set JAVA_HOME as C:\Program Files\Java\jdk1.6.0_31.
How to get this?
I got solution. this gives exactly the installed path.
FOR /F "skip=2 tokens=2*" %%A IN ('REG QUERY "HKLM\Software\JavaSoft\Java Development Kit" /v CurrentVersion') DO
set CurVer=%%B ECHO %CurVer%
FOR /F "skip=2 tokens=2*" %%A IN ('REG QUERY "HKLM\Software\JavaSoft\Java Development Kit\%CurVer%" /v JavaHome')
DO set JavaPath=%%B ECHO %JavaPath%
Path to Java 1.6 JavaHome:
#ECHO OFF &SETLOCAL
FOR /F "tokens=2*" %%a IN ('REG QUERY "HKEY_LOCAL_MACHINE\SOFTWARE\JavaSoft\Java Runtime Environment\1.6" /v JavaHome') DO set "JavaHome16=%%b"
ECHO %JavaHome16%
Path to Java 1.7 JavaHome:
#ECHO OFF &SETLOCAL
FOR /F "tokens=2*" %%a IN ('REG QUERY "HKEY_LOCAL_MACHINE\SOFTWARE\JavaSoft\Java Runtime Environment\1.7" /v JavaHome') DO set "JavaHome17=%%b"
ECHO %JavaHome17%
how about:
setx JAVA_HOME "path/to/it"
get it by doing %JAVA_HOME%
This will work if your JAVA_HOME is configured.save this as someName.bat and run.
echo
where java
pause
OK then use this, By running this will creates a text file where same place you put this bat contains the JAVA path
#ECHO OFF
SET TITLE=JavaHome.bat
TITLE=%TITLE%
SETLOCAL ENABLEDELAYEDEXPANSION
SET JDKBIN=\bin
SET JREBIN=\jre\bin
SET JBINARY=%JREBIN%\java.exe
SET SCRIPTDIR=%~dp0
SET SCRIPTDIR=%SCRIPTDIR:~0,-1%
IF EXIST "%SCRIPTDIR%\javahome.txt" (
ECHO.
ECHO JDK home already set in javahome.txt file.
GOTO :LOCKFILE
)
IF DEFINED JAVA_HOME (
ECHO.
ECHO JAVA_HOME is already set to !JAVA_HOME!
CALL :STRIP "!JAVA_HOME!">"!SCRIPTDIR!\javahome.txt"
ECHO Created !SCRIPTDIR!\javahome.txt file containing JAVA_HOME
GOTO :END
)
SET "dir=%~f0"
:DIRLOOP
CALL :FGETDIR "%dir%"
IF EXIST "%dir%\%JBINARY%" (
ECHO Parent directory search found JAVA_HOME at %dir%
GOTO :SEARCHSET
)
IF "%dir:~-1%" == ":" (
ECHO Parent directory search reached root and "%JBINARY%" was not found.
GOTO :REGISTRY
)
GOTO :DIRLOOP
:SEARCHSET
SET JAVA_HOME=%dir%
ECHO %JAVA_HOME%>javahome.txt
ECHO Created file %SCRIPTDIR%\javahome.txt with value %JAVA_HOME%
GOTO :END
:REGISTRY
:: registry search section
:: runs only when JAVA_HOME not set, file search fails, and javahome.txt doesn't exist
ECHO Searching registry for JAVA_HOME...
ECHO. 2>merged.txt
ECHO. 2>list.txt
ECHO. 2>uniquelist.txt
IF NOT EXIST reg32.txt ECHO. 2>reg32.txt
IF NOT EXIST reg64.txt ECHO. 2>reg64.txt
START /w REGEDIT /e reg32.txt "HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\JavaSoft\Java Development Kit"
TYPE reg32.txt | FIND "JavaHome" > merged.txt
START /w REGEDIT /e reg64.txt "HKEY_LOCAL_MACHINE\SOFTWARE\JavaSoft\Java Development Kit"
TYPE reg64.txt | FIND "JavaHome" >> merged.txt
FOR /f "tokens=2 delims==" %%x IN (merged.txt) DO (
CALL :STRIP "%%~x" >>list.txt
)
FOR /F "tokens=* delims= " %%a IN (list.txt) DO (
SET str=%%a
FIND /I ^"!str!^" list.txt>nul
FIND /I ^"!str!^" uniquelist.txt>nul
IF ERRORLEVEL 1 ECHO !str!>>uniquelist.txt
)
:PROMPT
ECHO Select a JDK from the list:
SET /A COUNT=0
FOR /f "tokens=1,* delims=" %%y IN (uniquelist.txt) DO (
SET /A COUNT += 1
ECHO !COUNT!: %%~y
)
SET /P NUMBER=Type a number here:
IF "%NUMBER%" GTR "%COUNT%" GOTO :PROMPT
SET /A COUNT=0
FOR /f "tokens=1,* delims=" %%z IN (uniquelist.txt) DO (
SET /A COUNT += 1
IF !COUNT!==!NUMBER! (
SET JAVA_HOME=%%~z
)
)
ECHO %JAVA_HOME%>javahome.txt
GOTO CLEANUP
:: batch functions section
:FGETDIR
SET "dir=%~dp1"
SET "dir=%dir:~0,-1%"
EXIT /B 0
:STRIP
REM Strip quotes and extra backslash from string
SET n=%~1
SET n=%n:\\=\%
SET n=%n:"=%
IF NOT "%n%"=="" ECHO %n%
GOTO :EOF
:: cleanup and end
:CLEANUP
REM cleanup of registry search
DEL /Q merged.txt
DEL /Q list.txt
DEL /Q uniquelist.txt
DEL /Q reg32.txt
DEL /Q reg64.txt
GOTO :LOCKFILE
:: if all fails
:FAILED
IF NOT DEFINED JAVA_HOME (
ECHO Error: JAVA_HOME not set in system vars, file search failed, && javahome.txt didn't exist.
GOTO :END
)
:LOCKFILE
ECHO.
SET /P JAVA_HOME=<"%SCRIPTDIR%\javahome.txt"
ECHO The file %SCRIPTDIR%\javahome.txt shows JAVA_HOME to be %JAVA_HOME%
:END
FOR /l %%a in (30,-1,1) do (TITLE %TITLE% -- Closing in %%as&ping -n 2 -w 1 127.0.0.1>NUL)
FYI : original reference: https://gist.github.com/djangofan/1445440
I need to know where JDK is located on my machine.
On running Java -version in cmd, it shows the version as '1.6.xx'.
To find the location of this SDK on my machine I tried using echo %JAVA_HOME% but it is only showing 'JAVA_HOME' (as there is no 'JAVA_PATH' var set in my environment variables).
If you are using Linux/Unix/Mac OS X:
Try this:
$ which java
Should output the exact location.
After that, you can set JAVA_HOME environment variable yourself.
In my computer (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
If you are using Windows:
c:\> for %i in (java.exe) do #echo. %~$PATH:i
Windows > Start > cmd >
C:> for %i in (javac.exe) do #echo. %~$PATH:i
If you have a JDK installed, the Path is displayed,
for example: C:\Program Files\Java\jdk1.6.0_30\bin\javac.exe
In Windows at the command prompt
where javac
Command line:
Run where java on Command Prompt.
GUI:
On Windows 10 you can find out the path by going to Control Panel > Programs > Java. In the panel that shows up, you can find the path as demonstrated in the screenshot below. In the Java Control Panel, go to the 'Java' tab and then click the 'View' button under the description 'View and manage Java Runtime versions and settings for Java applications and applets.'
This should work on Windows 7 and possibly other recent versions of Windows.
In windows the default is: C:\Program Files\Java\jdk1.6.0_14 (where the numbers may differ, as they're the version).
Java installer puts several files into %WinDir%\System32 folder (java.exe, javaws.exe and some others). When you type java.exe in command line or create process without full path, Windows runs these as last resort if they are missing in %PATH% folders.
You can lookup all versions of Java installed in registry. Take a look at HKLM\SOFTWARE\JavaSoft\Java Runtime Environment and HKLM\SOFTWARE\Wow6432Node\JavaSoft\Java Runtime Environment for 32-bit java on 64 bit Windows.
This is how java itself finds out different versions installed. And this is why both 32-bit and 64-bit version can co-exist and works fine without interfering.
Plain and simple on Windows platforms:
where java
Under Windows, you can use
C:>dir /b /s java.exe
to print the full path of each and every "java.exe" on your C: drive, regardless of whether they are on your PATH environment variable.
The batch script below will print out the existing default JRE. It can be easily modified to find the JDK version installed by replacing the Java Runtime Environment with 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
In a Windows command prompt, just type:
set java_home
Or, if you don't like the command environment, you can check it from:
Start menu > Computer > System Properties > Advanced System Properties. Then open Advanced tab > Environment Variables and in system variable try to find JAVA_HOME.
Powershell one liner:
$p='HKLM:\SOFTWARE\JavaSoft\Java Development Kit'; $v=(gp $p).CurrentVersion; (gp $p/$v).JavaHome
In Windows PowerShell you can use the Get-Command function to see where Java is installed:
Get-Command -All java
Or
gcm -All java
The -All part makes sure to show all places it appears in the Path lookup. Below is example output.
PS C:> gcm -All java
CommandType Name Version Source
----------- ---- ------- ------
Application java.exe 8.0.202.8 C:\Program Files (x86)\Common Files\Oracle\Java\jav...
Application java.exe 8.0.131... C:\ProgramData\Oracle\Java\javapath\java.exe
Run this program from commandline:
// File: Main.java
public class Main {
public static void main(String[] args) {
System.out.println(System.getProperty("java.home"));
}
}
$ javac Main.java
$ java Main
More on Windows... variable java.home is not always the same location as the binary that is run.
As Denis The Menace says, the installer puts Java files into Program Files, but also java.exe into System32. With nothing Java related on the path java -version can still work. However when PeterMmm's program is run it reports the value of Program Files as java.home, this is not wrong (Java is installed there) but the actual binary being run is located in System32.
One way to hunt down the location of the java.exe binary, add the following line to PeterMmm's code to keep the program running a while longer:
try{Thread.sleep(60000);}catch(Exception e) {}
Compile and run it, then hunt down the location of the java.exe image. E.g. in Windows 7 open the task manager, find the java.exe entry, right click and select 'open file location', this opens the exact location of the Java binary. In this case it would be System32.
Have you tried looking at your %PATH% variable. That's what Windows uses to find any executable.
Just execute the set command in your command line. Then you see all the environments variables you have set.
Or if on Unix you can simplify it:
$ set | grep "JAVA_HOME"
This is OS specific. On Unix:
which java
will display the path to the executable. I don't know of a Windows equivalent, but there you typically have the bin folder of the JDK installation in the system PATH:
echo %PATH%
On macOS, run:
cd /tmp && echo 'public class Main {public static void main(String[] args) {System.out.println(System.getProperty("java.home"));}}' > Main.java && javac Main.java && java Main
On my machine, this prints:
/Library/Java/JavaVirtualMachines/jdk-9.0.4.jdk/Contents/Home
Note that running which java does not show the JDK location, because the java command is instead part of JavaVM.framework, which wraps the real JDK:
$ which java
/usr/bin/java
/private/tmp
$ ls -l /usr/bin/java
lrwxr-xr-x 1 root wheel 74 14 Nov 17:37 /usr/bin/java -> /System/Library/Frameworks/JavaVM.framework/Versions/Current/Commands/java
None of these answers are correct for Linux if you are looking for the home that includes the subdirs such as: bin, docs, include, jre, lib, etc.
On Ubuntu for openjdk1.8.0, this is in:
/usr/lib/jvm/java-1.8.0-openjdk-amd64
and you may prefer to use that for JAVA_HOME since you will be able to find headers if you build JNI source files. While it's true which java will provide the binary path, it is not the true JDK home.
I have improved munsingh's answer above by testing for the registry key in 64-bit and 32-bit registries, if needed:
::- Test for the registry location
SET VALUE=CurrentVersion
SET KEY_1="HKLM\SOFTWARE\JavaSoft\Java Development Kit"
SET KEY_2=HKLM\SOFTWARE\JavaSoft\JDK
SET REG_1=reg.exe
SET REG_2="C:\Windows\sysnative\reg.exe"
SET REG_3="C:\Windows\syswow64\reg.exe"
SET KEY=%KEY_1%
SET REG=%REG_1%
%REG% QUERY %KEY% /v %VALUE% 2>nul
IF %ERRORLEVEL% EQU 0 GOTO _set_value
SET KEY=%KEY_2%
SET REG=%REG_1%
%REG% QUERY %KEY% /v %VALUE% 2>nul
IF %ERRORLEVEL% EQU 0 GOTO _set_value
::- %REG_2% is for 64-bit installations, using "C:\Windows\sysnative"
SET KEY=%KEY_1%
SET REG=%REG_2%
%REG% QUERY %KEY% /v %VALUE% 2>nul
IF %ERRORLEVEL% EQU 0 GOTO _set_value
SET KEY=%KEY_2%
SET REG=%REG_2%
%REG% QUERY %KEY% /v %VALUE% 2>nul
IF %ERRORLEVEL% EQU 0 GOTO _set_value
::- %REG_3% is for 32-bit installations on a 64-bit system, using "C:\Windows\syswow64"
SET KEY=%KEY_1%
SET REG=%REG_3%
%REG% QUERY %KEY% /v %VALUE% 2>nul
IF %ERRORLEVEL% EQU 0 GOTO _set_value
SET KEY=%KEY_2%
SET REG=%REG_3%
%REG% QUERY %KEY% /v %VALUE% 2>nul
IF %ERRORLEVEL% EQU 0 GOTO _set_value
:_set_value
FOR /F "tokens=2,*" %%a IN ('%REG% QUERY %KEY% /v %VALUE%') DO (
SET JDK_VERSION=%%b
)
SET KEY=%KEY%\%JDK_VERSION%
SET VALUE=JavaHome
FOR /F "tokens=2,*" %%a IN ('%REG% QUERY %KEY% /v %VALUE%') DO (
SET JAVAHOME=%%b
)
ECHO "%JAVAHOME%"
::- SETX JAVA_HOME "%JAVAHOME%"
reference for access to the 64-bit registry
Maybe the above methods work... I tried some and didn't for me. What did was this :
Run this in terminal :
/usr/libexec/java_home
Simple method (Windows):
Open an application using java.
press ctrl + shift + esc
Right click on OpenJDK platform binary. Click open file location.
Then it will show java/javaw.exe then go to the top where it shows the folder and click on the jdk then right copy the path, boom. (Wont work for apps using bundled jre paths/runtimes, because it will show path to the bundled runtime)
in Windows cmd:
set "JAVA_HOME"
#!/bin/bash
if [[ $(which ${JAVA_HOME}/bin/java) ]]; then
exe="${JAVA_HOME}/bin/java"
elif [[ $(which java) ]]; then
exe="java"
else
echo "Java environment is not detected."
exit 1
fi
${exe} -version
For windows:
#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
This link might help to explain how to find java executable from bash: http://srcode.org/2014/05/07/detect-java-executable/
Script for 32/64 bit Windows.
#echo off
setlocal enabledelayedexpansion
::- Get the Java Version
set KEY="HKLM\SOFTWARE\JavaSoft\Java Runtime Environment"
set KEY64="HKLM\SOFTWARE\WOW6432Node\JavaSoft\Java Runtime Environment"
set VALUE=CurrentVersion
reg query %KEY% /v %VALUE% 2>nul || (
set KEY=!KEY64!
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 KEY64="HKLM\SOFTWARE\WOW6432Node\JavaSoft\Java Runtime Environment\%JRE_VERSION%"
set VALUE=JavaHome
reg query %KEY% /v %VALUE% 2>nul || (
set KEY=!KEY64!
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