Discover from a batch file where is Java installed?

flybywire picture flybywire · Mar 12, 2009 · Viewed 20.3k times · Source

I want to set the JAVA_HOME variable from a batch script

Answer

Patrick Cuff picture Patrick Cuff · Mar 12, 2009

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%
)