Discover from a batch file where is Java installed?
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 offfor /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%)
See Get the current Java version from a BAT file to get the current Java installation based on the infos stored in the registry.
This solution depends on the JDK being installed under %ProgramFiles%\Java, for example C:\Program Files\Java\jdk1.6.0_18. You can change the line "set JDK_Version=1.6" to the version you want to use such as "set JDK_Version=1.5".
Assuming that the latest version of JDK would be at the bottom of the list (jdk%jdk_Version%*) the latest version available should be set as JAVA_HOME. If the JDK could not be found JAVA_HOME will not be changed. If the JDK could not be found and JAVA_HOME doesn't have a value the script will display an error message.
@echo offrem set the version of jdk you would like to use (1.4, 1.5, 1.6, etc)set JDK_Version=1.6echo.echo Locating JDK %JDK_Version%for /d %%i in ("%ProgramFiles%\Java\jdk%jdk_Version%*") do (set Located=%%i)rem check if JDK was locatedif "%Located%"=="" goto elserem if JDK located display message to userrem update %JAVA_HOME%set JAVA_HOME=%Located%echo Located JDK %jdk_Version%echo JAVA_HOME has been set to:echo %JAVA_HOME%goto endif:elserem if JDK was not locatedrem if %JAVA_HOME% has been defined then use the existing valueecho Could not locate JDK %JDK_Version%if "%JAVA_HOME%"=="" goto NoExistingJavaHomeecho Existing value of JAVA_HOME will be used:echo %JAVA_HOME%goto endif:NoExistingJavaHomerem display message to the user that %JAVA_HOME% is not availableecho No Existing value of JAVA_HOME is availablegoto endif:endifrem clear the variables used by this scriptset JDK_Version=set Located=