Get java version from batch file

后端 未结 5 1316
悲&欢浪女
悲&欢浪女 2020-12-01 15:09

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         


        
相关标签:
5条回答
  • 2020-12-01 15:29

    it should be java -version // if environment path is already set

    or %JAVA_HOME%/bin/java -version //if path is not already set

    0 讨论(0)
  • 2020-12-01 15:37

    Within a block statement, %var% would be echoed as the value of var BEFORE the block was entered.

    Move the echo outside of the block or echo %%g or call echo %%javaver%% or invoke SETLOCAL enabledelayedexpansion and echo !javaver!

    0 讨论(0)
  • 2020-12-01 15:40
    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%\bin\
    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).

    0 讨论(0)
  • 2020-12-01 15:45

    it will be surly idiot but why do not just print JAVA_HOME path ?

    0 讨论(0)
  • 2020-12-01 15:49

    You can do this with awk:

    >java -fullversion 2>&1|awk "{print $NF}"
    "1.7.0_21-b11"
    
    >java -fullversion 2>&1|awk -F\" "{print $(NF-1)}"
    1.7.0_21-b11
    

    Script example:

    @ECHO OFF &SETLOCAL
    FOR /f %%a IN ('java -fullversion 2^>^&1^|awk "{print $NF}"') DO SET "javaversion=%%a"
    IF DEFINED javaversion (ECHO java version: %javaversion%) ELSE ECHO java NOT found
    

    output is: java version: "1.7.0_21-b11"
    awk for Windows

    0 讨论(0)
提交回复
热议问题