Sujay
Sujay

Reputation: 6783

Java Version in a batch file

My question, is extremely similar to the following SO question: How to get Java Version from batch script?

In fact, it did almost solve my problem. The only difference is that I've to check the Java version based on %JAVA_HOME%, which the user is free to modify. The issue that I'm facing is with this code:

@ECHO OFF
SETLOCAL enableextensions enabledelayedexpansion

IF "%JAVA_HOME%"=="" (
    @ECHO Please set JAVA_HOME environment variable
    EXIT /B
) 

@echo "%JAVA_HOME%"

REM Checking JAVA_VERSION
SET JAVA_VERSION=
FOR /f "tokens=3" %%g in ('"%JAVA_HOME%"\bin\java -version 2^>^&1 ^| findstr /i "version"') do (
        SET "JAVA_VERSION=%%g"
)

%JAVA_HOME%% in my system points to "C:\Program Files\jdk1.7.0_25" (notice the space in the path)

Even with the quotes, I get the following error in command line:

'C:\Program' is not recognized as an internal or external command, operable program or batch file.

Any idea as to how to solve this problem? (The comments to the aforementioned article also mentions this issue). I'm working on a Windows 7 machine

Upvotes: 2

Views: 8519

Answers (3)

Sean McCallum
Sean McCallum

Reputation: 158

I had a similar problem, take a look at my QA: How to get Java version in a batch script subroutine?

From my answer:

It seems that piping the output to findstr was stripping the quotes for some reason.

I managed to fix the problem without Epic_Tonic's workaround (which would be very difficult to do with a path as a parameter).


This should work in your case:

set first=1
for /f "tokens=3" %%g in ('"%JAVA_HOME%\bin\java" -version 2^>^&1') do (
    if !first!==1 echo %%~g
    set first=0
)

Note: first is for only searching the first line of java -version's output (reference).

Upvotes: 0

Epic_Tonic
Epic_Tonic

Reputation: 96

Edit the %JAVA_HOME% Variable into:

C:\"Program Files"\jdk1.7.0_25

if you want it automated, type

set %JAVA_HOME%=C:\"Program Files"\jdk1.7.0_25

REASON WHY: The batch file does not accept the quotes; It is identifying them as a single file. So it attempts to find "C:\Program Files\jdk1.7.0_25" NOT as a folder path, but as a folder NAME in your root folder. If you type in C:\"Program Files"\jdk1.7.0.25 it identifies that "Program Files" is a single file. If there are no redirection operators, It would think that the path would be like this; C:\Program\Files\jdk1.7.0_25. It worked for me; It should probably work for you.

Hope that helped

-SonorousTwo

Upvotes: 1

Endoro
Endoro

Reputation: 37569

FOR /f "tokens=3" %%g in ('"%JAVA_HOME%\bin\java" -version 2^>^&1 ^| findstr /i "version"') do (
        SET "JAVA_VERSION=%%g"
)

Upvotes: 3

Related Questions