Java – How to Discover Installation Path from a Batch File
batch-filejavajava-homewindows
I want to set the JAVA_HOME variable from a batch script
Best Answer
This snippet will search the current PATH for java.exe, and print out where it was found:
for /f %%j in ("java.exe") do @echo.%%~dp$PATH:j
On my system this gives me
C:\WINDOWS\system32\
Using this you can set JAVA_HOME as follows:
@echo off
for /f %%j in ("java.exe") do (
set JAVA_HOME=%%~dp$PATH:j
)
if %JAVA_HOME%.==. (
@echo java.exe not found
) else (
@echo JAVA_HOME = %JAVA_HOME%
)
@echo off
setlocal enableextensions disabledelayedexpansion
rem Where to find java information in registry
set "javaKey=HKLM\SOFTWARE\JavaSoft\Java Runtime Environment"
rem Get current java version
set "javaVersion="
for /f "tokens=3" %%v in ('reg query "%javaKey%" /v "CurrentVersion" 2^>nul') do set "javaVersion=%%v"
rem Test if a java version has been found
if not defined javaVersion (
echo Java version not found
goto endProcess
)
rem Get java home for current java version
set "javaDir="
for /f "tokens=2,*" %%d in ('reg query "%javaKey%\%javaVersion%" /v "JavaHome" 2^>nul') do set "javaDir=%%e"
if not defined javaDir (
echo Java directory not found
) else (
echo JAVA_HOME : %javaDir%
)
:endProcess
endlocal
Best Answer
This snippet will search the current PATH for java.exe, and print out where it was found:
On my system this gives me
Using this you can set JAVA_HOME as follows: