Java – How to Discover Installation Path from a Batch File

batch-filejavajava-homewindows

I want to set the JAVA_HOME variable from a batch script

Best Answer

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