Michael Sobczak
Michael Sobczak

Reputation: 1085

Finding Java CurrentVersion in the Windows 7 registry

I support an old Java client application that runs fine on Windows XP but not Windows 7 32 bit. The problem is in the BAT file used to launch the application. The BAT file contains code that queries the registry for the CurrentVersion of Java and then uses that value to determine the path of that version of Java on the user's computer. This is needed in order to include rt.jar on the CLASSPATH when the Java client application is launched. The following code works fine on Windows XP, but on Windows 7 it returns:

"HKLM\SOFTWARE\JavaSoft\Java Runtime Environment"\CurrentVersion not found.

:find_java
setlocal ENABLEEXTENSIONS
set KEY_NAME="HKLM\SOFTWARE\JavaSoft\Java Runtime Environment"
set VALUE_NAME=CurrentVersion

::
:: get the current version
::
FOR /F "usebackq skip=4 tokens=3" %%A IN (`REG QUERY "HKLM\SOFTWARE\JavaSoft\Java Runtime Environment" /v CurrentVersion 2^>nul`) DO (
    set ValueValue=%%A
)

if defined ValueValue (

    @echo the current Java runtime is  %ValueValue%
) else (
    @echo %KEY_NAME%\%VALUE_NAME% not found.
    goto return
)

set JAVA_CURRENT="HKLM\SOFTWARE\JavaSoft\Java Runtime Environment\%ValueValue%"
set JAVA_HOME=JavaHome

::
:: get the javahome
::
FOR /F "usebackq skip=4 tokens=3,4" %%A IN (`REG QUERY %JAVA_CURRENT% /v %JAVA_HOME% 2^>nul`) DO (
    set JAVA_PATH=%%A %%B
)
set JAVA_PATH=%JAVA_PATH:Program Files=Progra~1%
echo using %JAVA_PATH%
set JAVA_HOME=%JAVA_PATH%
echo.
:return
goto start

I'm not savvy when it comes to complex DOS command programming. Any clues on how I can update this code so that it will work under Windows 7 (32 bit)?

Upvotes: 1

Views: 8760

Answers (1)

MC ND
MC ND

Reputation: 70923

Maybe this could help

@echo off 
    setlocal enableextensions disabledelayedexpansion

    :: possible locations under HKLM\SOFTWARE of JavaSoft registry data
    set "javaNativeVersion="
    set "java32ON64=Wow6432Node\"

    :: for variables
    ::    %%k = HKLM\SOFTWARE subkeys where to search for JavaSoft key
    ::    %%j = full path of "Java Runtime Environment" key under %%k
    ::    %%v = current java version
    ::    %%e = path to java

    set "javaDir="
    set "javaVersion="
    for %%k in ( "%javaNativeVersion%" "%java32ON64%") do if not defined javaDir (
        for %%j in (
            "HKLM\SOFTWARE\%%~kJavaSoft\Java Runtime Environment"
        ) do for /f "tokens=3" %%v in (
            'reg query "%%~j" /v "CurrentVersion" 2^>nul ^| find /i "CurrentVersion"'
        ) do for /f "tokens=2,*" %%d in (
            'reg query "%%~j\%%v" /v "JavaHome"   2^>nul ^| find /i "JavaHome"'
        ) do ( set "javaDir=%%~e" & set "javaVersion=%%v" )
    )

    if not defined javaDir (
        echo Java not found
    ) else (
        echo JAVA_HOME="%javaDir%"
        echo JAVA_VERSION="%javaVersion%"
    )

    endlocal

Upvotes: 5

Related Questions