Discover from a batch file where is Java installed

2020-07-03 09:12发布

I want to set the JAVA_HOME variable from a batch script

9条回答
爱情/是我丢掉的垃圾
2楼-- · 2020-07-03 09:53

While not perfect, you can use the following to discover the current JRE folder:

for /d %%i in ("\Program Files\Java\jre*") do set JAVA_HOME=%%i

If it's the JDK you want, use:

for /d %%i in ("\Program Files\Java\jdk*") do set JAVA_HOME=%%i`

For a more robust solution based on checking the Windows Registry, use:

set KeyName=HKEY_LOCAL_MACHINE\SOFTWARE\JavaSoft\Java Runtime Environment
set Cmd=reg query "%KeyName%" /s
for /f "tokens=2*" %%i in ('%Cmd% ^| find "JavaHome"') do set JAVA_HOME=%%j

For the JDK, you'll need this line instead:

set KeyName=HKEY_LOCAL_MACHINE\SOFTWARE\JavaSoft\Java Development Kit
查看更多
The star\"
3楼-- · 2020-07-03 09:56

This doesn't search the entire hard drive. It only searches the parent directory tree and so its much faster than using "dir java.exe /B /S".

@ECHO off
ECHO ------------------------------------------------------------------
ECHO  Define the location of an existing JDK install by 
ECHO  searching for Javasoft JDK distrobution in parent 
ECHO  directories.
ECHO.
ECHO  Script does not add trailing slash.
ECHO ------------------------------------------------------------------
IF DEFINED JAVA_HOME (
  ECHO JAVA_HOME is already set.
  GOTO :JHSET
)
SET matchobject=Javasoft\bin\java.exe
SET "dir=%~f0"
:LOOP
CALL :FGETDIR "%dir%"
IF EXIST "%dir%\%matchobject%" (
  ECHO Found JAVA_HOME at %dir%\
  GOTO :HOMESET
)
IF "%dir:~-1%" == ":" (
  ECHO Reached root and directory containing "%matchobject%" not found.
  GOTO :EOF
)
GOTO :LOOP
:HOMESET
SET JAVA_HOME=%dir%
GOTO :JHSET
:: function section
:FGETDIR
SET "dir=%~dp1"
SET "dir=%dir:~0,-1%"
EXIT /B 0
:: end function section
:JHSET
:: Does JAVA_HOME have a trailing slash? If so remove it.
IF !JAVA_HOME:~-1!==\ SET JAVA_HOME=!JAVA_HOME:~0,-1!
ECHO JAVA_HOME is %JAVA_HOME%
ECHO Will close in a few seconds...
ping -n 60 127.0.0.1>nul
查看更多
女痞
4楼-- · 2020-07-03 09:59

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%
)
查看更多
登录 后发表回答