Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
783 views
in Technique[技术] by (71.8m points)

cmd - Get java version from batch file

How to get java version and want to get '6' out of java version from batch file. I tried below script, but it didn't work.

    REM check java exists using JAVA_HOME system variable

if "%JAVA_HOME%" == "" (
ECHO Installing java
start /w jdk.exe /s
SETX -m JAVA_HOME "C:Program FilesJavajdk1.6.0_31"
ECHO java installed successfully
) ELSE (
ECHO checking java version
goto check_java_version
)

REM check java version using JAVA_HOME system variable
:check_java_version
set PATH=%PATH%;%JAVA_HOME%in
for /f tokens^=2-5^ delims^=.-_^" %%j in ('%JAVA_HOME%/bin/java -version 2^>^&1') do set "jver=%%j%%k%%l%%m"
echo %jver%

JAVA_HOME has "C:Program FilesJavajdk1.6.0_31" value.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
for /f tokens^=2-5^ delims^=.-_^" %j in ('java -fullversion 2^>^&1') do @set "jver=%j%k%l%m"

This will store the java version into jver variable and as integer And you can use it for comparisons .E.G

if %jver% LSS 16000 echo not supported version

.You can use more major version by removing %k and %l and %m.This command prompt version.

For .bat use this:

@echo off
PATH %PATH%;%JAVA_HOME%in
for /f tokens^=2-5^ delims^=.-_^" %%j in ('java -fullversion 2^>^&1') do set "jver=%%j%%k%%l%%m"

According to my tests this is the fastest way to get the java version from bat (as it uses only internal commands and not external ones as FIND,FINDSTR and does not use GOTO which also can slow the script). Some JDK vendors does not support -fullversion switch or their implementation is not the same as this one provided by Oracle (better avoid them).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...