在Windows 7注册表中查找Java CurrentVersion

时间:2014-11-13 13:35:04

标签: java windows batch-file registry

我支持在Windows XP上运行良好而不是Windows 7 32位的旧Java客户端应用程序。问题出在用于启动应用程序的BAT文件中。 BAT文件包含用于查询注册表以查找Java的CurrentVersion的代码,然后使用该值来确定用户计算机上该版本Java的路径。这是在Java客户端应用程序启动时在CLASSPATH上包含rt.jar所必需的。以下代码在Windows XP上运行正常,但在Windows 7上它返回:

" HKLM \ SOFTWARE \ JavaSoft \ Java运行时环境" \ CurrentVersion未找到。

: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

在复杂的DOS命令编程方面,我并不精明。有关如何更新此代码以便它在Windows 7(32位)下工作的任何线索?

1 个答案:

答案 0 :(得分:4)

也许这可以帮助

@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