0

I have a test.bat file where i need to write a script to check PATH VARIABLE for java already installed or not ?

 Conditions :-

  1) If yes then 
       a) Check for the java version .
       b) Check for JAVA_HOME env variable :-
           i) if no , create it.
           ii) if yes , get the JAVA_HOME value.
  2) If No then
   set JAVA_HOME to local path (embedded)



 I know the commands like :-
      For version
         -> java -version

      For variable path 
         -> echo %path%

      For Java variable path
         -> echo %JAVA_HOME%

But how to write script for these condition in batch file i.e .bat ? I'm very new to this so kindly give me your valuable answers or helpful links.

Little bird
  • 1,106
  • 7
  • 28
  • 58

3 Answers3

3

You can check with something like that:

@echo off
if defined JAVA_HOME (
if exist "%JAVA_HOME%\bin\javac.exe" goto okJavac
)

echo Java not found
exit 1

%okJavac
echo Java path "%JAVA_HOME%"
rem the end of your script
BenMorel
  • 34,448
  • 50
  • 182
  • 322
Alexxx
  • 766
  • 1
  • 11
  • 19
  • :I tried your code but after double clicking on the test.bat file but i could see a glimpse of terminal which comes and disappear .Even i checked JAVA_HOME path location and its in right location as what you defined in your code. How can i resolve this problem ? – Little bird Aug 05 '13 at 10:48
  • @Tala : any solutions for this ? – Little bird Aug 05 '13 at 10:55
  • Start your bat from cmd with K key added : `/K yourfile.bat` – Tala Aug 05 '13 at 10:57
  • i tried :okJavac instead of %okJavac ....and its working . thanx Tala and Alexxx :) – Little bird Aug 05 '13 at 11:14
2

try this:

@ECHO OFF &SETLOCAL
for /f tokens^=2delims^=^"  %%a in ('java -version 2^>^&1') do set "JavaVersion=%%a"
IF NOT DEFINED JavaVersion ECHO no Java installed & GOTO :EOF
FOR /f "tokens=2delims=." %%a IN ("%JavaVersion%") DO SET "sub=%%a"

IF DEFINED ProgramFiles(x86) (
    IF NOT DEFINED JAVA_HOME SET "JAVA_HOME=%ProgramFiles(x86)%\Java\jre%sub%\bin"
) ELSE (
    IF NOT DEFINED JAVA_HOME SET "JAVA_HOME=%ProgramFiles%\Java\jre%sub%\bin"
)

SET "java_home"
PAUSE
Endoro
  • 37,015
  • 8
  • 50
  • 63
1

Check the appropriate MS guide for working with the batch files. You can check the output of the java -version in the way described here

Community
  • 1
  • 1
wanderlust
  • 1,826
  • 1
  • 21
  • 25