我想从批处理脚本中设置JAVA_HOME变量
此代码段将搜索当前PATH以查找java.exe,并打印出找到它的位置:
for /f %%j in ("java.exe") do @echo.%%~dp$PATH:j
在我的系统上,这给了我
C:\ WINDOWS\SYSTEM32 \
使用此方法,您可以按如下方式设置JAVA_HOME:
@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% )
请参阅从BAT文件获取当前Java版本,以根据存储在注册表中的信息获取当前的Java安装.
此解决方案取决于在%ProgramFiles%\ Java下安装的JDK,例如C:\ Program Files\Java\jdk1.6.0_18.您可以将"set JDK_Version = 1.6"行更改为您要使用的版本,例如"set JDK_Version = 1.5".
假设最新版本的JDK位于列表的底部(jdk%jdk_Version%*),可用的最新版本应设置为JAVA_HOME.如果找不到JDK,JAVA_HOME将不会被更改.如果找不到JDK且JAVA_HOME没有值,则脚本将显示错误消息.
@echo off rem set the version of jdk you would like to use (1.4, 1.5, 1.6, etc) set JDK_Version=1.6 echo. echo Locating JDK %JDK_Version% for /d %%i in ("%ProgramFiles%\Java\jdk%jdk_Version%*") do (set Located=%%i) rem check if JDK was located if "%Located%"=="" goto else rem if JDK located display message to user rem update %JAVA_HOME% set JAVA_HOME=%Located% echo Located JDK %jdk_Version% echo JAVA_HOME has been set to: echo %JAVA_HOME% goto endif :else rem if JDK was not located rem if %JAVA_HOME% has been defined then use the existing value echo Could not locate JDK %JDK_Version% if "%JAVA_HOME%"=="" goto NoExistingJavaHome echo Existing value of JAVA_HOME will be used: echo %JAVA_HOME% goto endif :NoExistingJavaHome rem display message to the user that %JAVA_HOME% is not available echo No Existing value of JAVA_HOME is available goto endif :endif rem clear the variables used by this script set JDK_Version= set Located=
您可以使用存储在注册表中的值自动发现Java的安装位置并设置JAVA_HOME变量.
HKLM > Software > JavaSoft > Java Runtime Environment
在这个位置是一个名为CurrentVersion的Key.此版本按名称引用此级别的其中一个目录.打开目录会公开另一个名为JavaHome的键.JavaHome的值是一个文件系统路径,可用于定义环境变量JAVA_HOME.
在批处理文件中,您可以执行以下操作:
FOR /F "skip=2 tokens=2*" %%A IN ('REG QUERY "HKLM\Software\JavaSoft\Java Runtime Environment" /v CurrentVersion') DO set CurVer=%%B FOR /F "skip=2 tokens=2*" %%A IN ('REG QUERY "HKLM\Software\JavaSoft\Java Runtime Environment\%CurVer%" /v JavaHome') DO set JAVA_HOME=%%B
如果您想阅读更多内容,我已经编写了一个教程,描述了构建批处理文件以自动发现JAVA_HOME所需的内容.