java – Reliable Way to Find JRE Installation in Windows Bat File

batch-filejavawindow

When installing the latest JRE 7 on Windows, it no longer adds the command java to the system path. So just calling java --version in bat file fails in that case (despite that Java from java.com is installed).

What's a reliable way to find the java command installation directory in a windows bat file?

I've seen it in the following locations:

  • C:\Program Files\Java\jre6\bin\java.exe
  • C:\Program Files\Java\jre7\bin\java.exe
  • C:\Program Files (x86)\Java\jre7\bin\java.exe
  • Not tried JRE 8 yet.

Note: if there are multiple, I 'd like the default (or the latest – I don't care).

Best Answer

If it is installed, ask windows where it is

@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
Related Question