Set Java Major Version Number As A Variable - java

This is irritating. I am trying to incorporate a trigger in a script to run if the major version of Java is 1.6,1.7, etc.
In the line I am trying to set the variable in, I pull the Java version and pipe it to for with tokens and delims identified, resulting in the "do" as a set command for variable %jver%. However, echoing %jver% results in "echo is on". Why wont it set the variable? Everything looks legit until %jver% is used.
Yes, I double the percentages for the script. The code here is for use at the command prompt.
Here is the line:
%systemroot%\system32\java.exe -version 2>&1 | for /f "tokens=1-4 delims=. " %a in ('findstr /i "version"') do (set jver=%~c.%d)

#rao thank you for helping me discover an alternate solution to meet my intent.
My workaround solution to this is the following line:
for /f "tokens=1-4 delims=. " %a in ('java -version 2^>^&1 ^| findstr /i "version"') do (SET JVER=%~c.%d)

Looks this is answered in this post by Patrick Cuff
Here is the solution adding from mentioned original post
#echo off
setlocal
set VERSION6="1.6.0_21"
for /f "tokens=3" %%g in ('java -version 2^>^&1 ^| findstr /i "version"') do (
#echo Output: %%g
set JAVAVER=%%g
)
set JAVAVER=%JAVAVER:"=%
#echo Output: %JAVAVER%

Related

Wmic process call in for loop doesn't start the cmd

I am trying to retrieve the ProcessID of a Java app launched through a batch file. The problem is that the application does not start.
My code:
set cmd=java -jar XXXXXXX.jar XXXXXX.yml
for /f "tokens=2 delims==; " %%a in (' wmic process call create "%cmd%" ^| find "ProcessId" ') do set PID=%%a
start cmd /k echo %pid%
PAUSE
Batch files are pretty picky with whitespace.
Change this:
set cmd = java -jar XXXXXXX.jar XXXXXX.yml
To this:
set cmd=java -jar XXXXXXX.jar XXXXXX.yml
This works:
set cmd=notepad
for /f "tokens=2 delims==; " %%a in (' wmic process call create "%cmd%" ^| find "ProcessId" ') do set PID=%%a
start cmd /k echo %pid%
PAUSE
There may be something wrong with your jar file or perhaps java is not on your PATH. Try running your command directly at a command prompt to see if it works:
c:\>java -jar XXXXXXX.jar XXXXXX.yml
Also make sure that you use the full path to your jar file in your cmd otherwise the path will be relative to your system folder:
set cmd=java -jar c:\yourpath\XXXXXXX.jar XXXXXX.yml

Adding java output to echo string of bat file

I need to assign Standard out of java application added to an echo string of a bat file. Lets say java application writes "hello world" via System.out.println.
For an example I have a bat file mybat.bat.
#echo off
echo output=java -jar E:\FYP\MyApp\out\artifacts\MyApp_jar\MyApp_jar\MyApp.jar %1
which does not give the output=Hello world
How can I achieve that. Your help is really appreciated.
Thank You !
As far as I understand you - you want to assign the output of the java to variable.
May be this will do this for you:
#echo off
set "java_output="
setlocal enableDelayedExpansion
for /f "delims=" %%J in ('java -jar E:\FYP\MyApp\out\artifacts\MyApp_jar\MyApp_jar\MyApp.jar %1') do (
set "java_output=!java_output! %%J"
)
endlocal & set java_output=%java_output%
echo %java_output%
You need to use for command to get the output of a program and assign it to a variable.
#echo off
for /F "tokens=*" %%o in ('java -jar E:\FYP\MyApp\out\artifacts\MyApp_jar\MyApp_jar\MyApp.jar %1') do set output=%%o
echo %output%

Find java PID using batch

I need to know java process PID from Windows batch console.
#echo off
set p=%CD%
FOR /F "tokens=1" %%A IN ('"%JAVA_HOME%/bin/jps.exe -v"\|find "%p%"') DO SET str=%%A
echo str = "%str%"
Java process unique identifier is path from what it was executed.
Script executes jps, that returns all java process information, for example
9376 Jps -Denv.class.path=D:\tools\timesten\lib\ttjdbc6.jar; -Dapplication.home=C:\Program Files\Java\jdk1.6.0_24 -Xms8m
3856 -Dexe4j.semaphoreName=c:_program files (x86)_jetbrains_intellij idea community edition 12.0.1_bin_idea.exe -Dexe4j.moduleName=C:\Program Files (x86)\JetBrains\IntelliJ IDEA Community Edition 12....etc
Batch says that:
| was unexpected at this time.
Could you please said , how to correctly extract PID.
You have to escape the pipe like this ^| within a FOR statement, otherwise it tries to pipe the first half of the FOR statement into the second.
Also this is how I would find a PID.
for /f "tokens=2" %%a in ('tasklist ^| find "jps.exe") do set javapid=%%a
You can user command "tasklist" for show PID。
Correct script
"%JAVA_HOME%/bin/jps.exe" -v>temp.txt
for /f "tokens=1" %%f in ('find "%CD%" "temp.txt"') do set str=%%f
echo str=%str%

How to get Java Version from batch script?

I am trying to get '6' out of the java version output given below
java version "1.6.0_21"
Java(TM) SE Runtime Environment (build 1.6.0_21-b07)
Java HotSpot(TM) Client VM (build 17.0-b17, mixed mode, sharing)
For the same I wrote this batch script
set VERSION6="1.6.0_21"
java -version 2>&1 | findstr "version" >ab.txt
for /f "tokens=3" %%g in (ab.txt) do (
if not %%g == %VERSION6% echo %%g
echo %%g
)
%%g displays "1.6.0_21"
May someone guide me to correct direction? I am not much familiar with for /f.
#echo off
setlocal
set VERSION6="1.6.0_21"
for /f "tokens=3" %%g in ('java -version 2^>^&1 ^| findstr /i "version"') do (
#echo Output: %%g
set JAVAVER=%%g
)
set JAVAVER=%JAVAVER:"=%
#echo Output: %JAVAVER%
for /f "delims=. tokens=1-3" %%v in ("%JAVAVER%") do (
#echo Major: %%v
#echo Minor: %%w
#echo Build: %%x
)
endlocal
In the first for loop, "tokens=3" says that we're going to just use the third token from the command output. Rather than redirect the output of the java -version command to a file, we can run this command within the for loop itself. The carets (^) are escape characters, and are needed so we can embed the >, & and | symbols in the command string.
Within the body of the for loop, we set a new var, JAVAVER, so that we can do some manipulation of the version string later.
The set JAVAVER=%JAVAVER:"=% command removes the double quotes from around the version string.
The last for loop parses the java version string. delims=. says we're going to delimit tokens using periods. tokens=1-3 says we're going to pass the first three tokens from the string to the body of the loop. We can now get the components of the java version string using the explicit variable, %%v and the implied variables (next letters in the alphabet) %%w and %%x.
When I run this on my system I get:
Output: "1.6.0_24"
Output: 1.6.0_24
Major: 1
Minor: 6
Build: 0_24
I've made some modification to Patrick's answer so it works with Java 9, 10, etc.
This returns minor version for 1.x, and major version for Java 9, 10, etc.
#echo off
setlocal
rem We use the value the JAVACMD environment variable, if defined
rem and then try JAVA_HOME
set "_JAVACMD=%JAVACMD%"
if "%_JAVACMD"=="" (
if not "%JAVA_HOME%"=="" (
if exist "%JAVA_HOME%\bin\java.exe" set "_JAVACMD=%JAVA_HOME%\bin\java.exe"
)
)
if "%_JAVACMD%"=="" set _JAVACMD=java
rem Parses x out of 1.x; for example 8 out of java version 1.8.0_xx
rem Otherwise, parses the major version; 9 out of java version 9-ea
set JAVA_VERSION=0
for /f "tokens=3" %%g in ('%_JAVACMD% -Xms32M -Xmx32M -version 2^>^&1 ^| findstr /i "version"') do (
set JAVA_VERSION=%%g
)
set JAVA_VERSION=%JAVA_VERSION:"=%
for /f "delims=.-_ tokens=1-2" %%v in ("%JAVA_VERSION%") do (
if /I "%%v" EQU "1" (
set JAVA_VERSION=%%w
) else (
set JAVA_VERSION=%%v
)
)
#echo %JAVA_VERSION%
endlocal
echoes 8 or 17 etc.
This will extract the minor part of the version number:
java -version 2>&1 | awk '/version/ {print $3}' | awk -F . '{print $2}'
However, it may be better to extract the major.minor and match on that in case Oracle ever change the version number scheme again e.g.:
java -version 2>&1 | awk '/version/ {print $3}' | egrep -o '[0-9]+\.[0-9]+'
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).

How do I find where JDK is installed on my windows machine?

I need to know where JDK is located on my machine.
On running Java -version in cmd, it shows the version as '1.6.xx'.
To find the location of this SDK on my machine I tried using echo %JAVA_HOME% but it is only showing 'JAVA_HOME' (as there is no 'JAVA_PATH' var set in my environment variables).
If you are using Linux/Unix/Mac OS X:
Try this:
$ which java
Should output the exact location.
After that, you can set JAVA_HOME environment variable yourself.
In my computer (Mac OS X - Snow Leopard):
$ which java
/usr/bin/java
$ ls -l /usr/bin/java
lrwxr-xr-x 1 root wheel 74 Nov 7 07:59 /usr/bin/java -> /System/Library/Frameworks/JavaVM.framework/Versions/Current/Commands/java
If you are using Windows:
c:\> for %i in (java.exe) do #echo. %~$PATH:i
Windows > Start > cmd >
C:> for %i in (javac.exe) do #echo. %~$PATH:i
If you have a JDK installed, the Path is displayed,
for example: C:\Program Files\Java\jdk1.6.0_30\bin\javac.exe
In Windows at the command prompt
where javac
Command line:
Run where java on Command Prompt.
GUI:
On Windows 10 you can find out the path by going to Control Panel > Programs > Java. In the panel that shows up, you can find the path as demonstrated in the screenshot below. In the Java Control Panel, go to the 'Java' tab and then click the 'View' button under the description 'View and manage Java Runtime versions and settings for Java applications and applets.'
This should work on Windows 7 and possibly other recent versions of Windows.
In windows the default is: C:\Program Files\Java\jdk1.6.0_14 (where the numbers may differ, as they're the version).
Java installer puts several files into %WinDir%\System32 folder (java.exe, javaws.exe and some others). When you type java.exe in command line or create process without full path, Windows runs these as last resort if they are missing in %PATH% folders.
You can lookup all versions of Java installed in registry. Take a look at HKLM\SOFTWARE\JavaSoft\Java Runtime Environment and HKLM\SOFTWARE\Wow6432Node\JavaSoft\Java Runtime Environment for 32-bit java on 64 bit Windows.
This is how java itself finds out different versions installed. And this is why both 32-bit and 64-bit version can co-exist and works fine without interfering.
Plain and simple on Windows platforms:
where java
Under Windows, you can use
C:>dir /b /s java.exe
to print the full path of each and every "java.exe" on your C: drive, regardless of whether they are on your PATH environment variable.
The batch script below will print out the existing default JRE. It can be easily modified to find the JDK version installed by replacing the Java Runtime Environment with Java Development Kit.
#echo off
setlocal
::- Get the Java Version
set KEY="HKLM\SOFTWARE\JavaSoft\Java Runtime Environment"
set VALUE=CurrentVersion
reg query %KEY% /v %VALUE% 2>nul || (
echo JRE not installed
exit /b 1
)
set JRE_VERSION=
for /f "tokens=2,*" %%a in ('reg query %KEY% /v %VALUE% ^| findstr %VALUE%') do (
set JRE_VERSION=%%b
)
echo JRE VERSION: %JRE_VERSION%
::- Get the JavaHome
set KEY="HKLM\SOFTWARE\JavaSoft\Java Runtime Environment\%JRE_VERSION%"
set VALUE=JavaHome
reg query %KEY% /v %VALUE% 2>nul || (
echo JavaHome not installed
exit /b 1
)
set JAVAHOME=
for /f "tokens=2,*" %%a in ('reg query %KEY% /v %VALUE% ^| findstr %VALUE%') do (
set JAVAHOME=%%b
)
echo JavaHome: %JAVAHOME%
endlocal
In a Windows command prompt, just type:
set java_home
Or, if you don't like the command environment, you can check it from:
Start menu > Computer > System Properties > Advanced System Properties. Then open Advanced tab > Environment Variables and in system variable try to find JAVA_HOME.
Powershell one liner:
$p='HKLM:\SOFTWARE\JavaSoft\Java Development Kit'; $v=(gp $p).CurrentVersion; (gp $p/$v).JavaHome
In Windows PowerShell you can use the Get-Command function to see where Java is installed:
Get-Command -All java
Or
gcm -All java
The -All part makes sure to show all places it appears in the Path lookup. Below is example output.
PS C:> gcm -All java
CommandType Name Version Source
----------- ---- ------- ------
Application java.exe 8.0.202.8 C:\Program Files (x86)\Common Files\Oracle\Java\jav...
Application java.exe 8.0.131... C:\ProgramData\Oracle\Java\javapath\java.exe
Run this program from commandline:
// File: Main.java
public class Main {
public static void main(String[] args) {
System.out.println(System.getProperty("java.home"));
}
}
$ javac Main.java
$ java Main
More on Windows... variable java.home is not always the same location as the binary that is run.
As Denis The Menace says, the installer puts Java files into Program Files, but also java.exe into System32. With nothing Java related on the path java -version can still work. However when PeterMmm's program is run it reports the value of Program Files as java.home, this is not wrong (Java is installed there) but the actual binary being run is located in System32.
One way to hunt down the location of the java.exe binary, add the following line to PeterMmm's code to keep the program running a while longer:
try{Thread.sleep(60000);}catch(Exception e) {}
Compile and run it, then hunt down the location of the java.exe image. E.g. in Windows 7 open the task manager, find the java.exe entry, right click and select 'open file location', this opens the exact location of the Java binary. In this case it would be System32.
Have you tried looking at your %PATH% variable. That's what Windows uses to find any executable.
Just execute the set command in your command line. Then you see all the environments variables you have set.
Or if on Unix you can simplify it:
$ set | grep "JAVA_HOME"
This is OS specific. On Unix:
which java
will display the path to the executable. I don't know of a Windows equivalent, but there you typically have the bin folder of the JDK installation in the system PATH:
echo %PATH%
On macOS, run:
cd /tmp && echo 'public class Main {public static void main(String[] args) {System.out.println(System.getProperty("java.home"));}}' > Main.java && javac Main.java && java Main
On my machine, this prints:
/Library/Java/JavaVirtualMachines/jdk-9.0.4.jdk/Contents/Home
Note that running which java does not show the JDK location, because the java command is instead part of JavaVM.framework, which wraps the real JDK:
$ which java
/usr/bin/java
/private/tmp
$ ls -l /usr/bin/java
lrwxr-xr-x 1 root wheel 74 14 Nov 17:37 /usr/bin/java -> /System/Library/Frameworks/JavaVM.framework/Versions/Current/Commands/java
None of these answers are correct for Linux if you are looking for the home that includes the subdirs such as: bin, docs, include, jre, lib, etc.
On Ubuntu for openjdk1.8.0, this is in:
/usr/lib/jvm/java-1.8.0-openjdk-amd64
and you may prefer to use that for JAVA_HOME since you will be able to find headers if you build JNI source files. While it's true which java will provide the binary path, it is not the true JDK home.
I have improved munsingh's answer above by testing for the registry key in 64-bit and 32-bit registries, if needed:
::- Test for the registry location
SET VALUE=CurrentVersion
SET KEY_1="HKLM\SOFTWARE\JavaSoft\Java Development Kit"
SET KEY_2=HKLM\SOFTWARE\JavaSoft\JDK
SET REG_1=reg.exe
SET REG_2="C:\Windows\sysnative\reg.exe"
SET REG_3="C:\Windows\syswow64\reg.exe"
SET KEY=%KEY_1%
SET REG=%REG_1%
%REG% QUERY %KEY% /v %VALUE% 2>nul
IF %ERRORLEVEL% EQU 0 GOTO _set_value
SET KEY=%KEY_2%
SET REG=%REG_1%
%REG% QUERY %KEY% /v %VALUE% 2>nul
IF %ERRORLEVEL% EQU 0 GOTO _set_value
::- %REG_2% is for 64-bit installations, using "C:\Windows\sysnative"
SET KEY=%KEY_1%
SET REG=%REG_2%
%REG% QUERY %KEY% /v %VALUE% 2>nul
IF %ERRORLEVEL% EQU 0 GOTO _set_value
SET KEY=%KEY_2%
SET REG=%REG_2%
%REG% QUERY %KEY% /v %VALUE% 2>nul
IF %ERRORLEVEL% EQU 0 GOTO _set_value
::- %REG_3% is for 32-bit installations on a 64-bit system, using "C:\Windows\syswow64"
SET KEY=%KEY_1%
SET REG=%REG_3%
%REG% QUERY %KEY% /v %VALUE% 2>nul
IF %ERRORLEVEL% EQU 0 GOTO _set_value
SET KEY=%KEY_2%
SET REG=%REG_3%
%REG% QUERY %KEY% /v %VALUE% 2>nul
IF %ERRORLEVEL% EQU 0 GOTO _set_value
:_set_value
FOR /F "tokens=2,*" %%a IN ('%REG% QUERY %KEY% /v %VALUE%') DO (
SET JDK_VERSION=%%b
)
SET KEY=%KEY%\%JDK_VERSION%
SET VALUE=JavaHome
FOR /F "tokens=2,*" %%a IN ('%REG% QUERY %KEY% /v %VALUE%') DO (
SET JAVAHOME=%%b
)
ECHO "%JAVAHOME%"
::- SETX JAVA_HOME "%JAVAHOME%"
reference for access to the 64-bit registry
Maybe the above methods work... I tried some and didn't for me. What did was this :
Run this in terminal :
/usr/libexec/java_home
Simple method (Windows):
Open an application using java.
press ctrl + shift + esc
Right click on OpenJDK platform binary. Click open file location.
Then it will show java/javaw.exe then go to the top where it shows the folder and click on the jdk then right copy the path, boom. (Wont work for apps using bundled jre paths/runtimes, because it will show path to the bundled runtime)
in Windows cmd:
set "JAVA_HOME"
#!/bin/bash
if [[ $(which ${JAVA_HOME}/bin/java) ]]; then
exe="${JAVA_HOME}/bin/java"
elif [[ $(which java) ]]; then
exe="java"
else
echo "Java environment is not detected."
exit 1
fi
${exe} -version
For windows:
#echo off
if "%JAVA_HOME%" == "" goto nojavahome
echo Using JAVA_HOME : %JAVA_HOME%
"%JAVA_HOME%/bin/java.exe" -version
goto exit
:nojavahome
echo The JAVA_HOME environment variable is not defined correctly
echo This environment variable is needed to run this program.
goto exit
:exit
This link might help to explain how to find java executable from bash: http://srcode.org/2014/05/07/detect-java-executable/
Script for 32/64 bit Windows.
#echo off
setlocal enabledelayedexpansion
::- Get the Java Version
set KEY="HKLM\SOFTWARE\JavaSoft\Java Runtime Environment"
set KEY64="HKLM\SOFTWARE\WOW6432Node\JavaSoft\Java Runtime Environment"
set VALUE=CurrentVersion
reg query %KEY% /v %VALUE% 2>nul || (
set KEY=!KEY64!
reg query !KEY! /v %VALUE% 2>nul || (
echo JRE not installed
exit /b 1
)
)
set JRE_VERSION=
for /f "tokens=2,*" %%a in ('reg query %KEY% /v %VALUE% ^| findstr %VALUE%') do (
set JRE_VERSION=%%b
)
echo JRE VERSION: %JRE_VERSION%
::- Get the JavaHome
set KEY="HKLM\SOFTWARE\JavaSoft\Java Runtime Environment\%JRE_VERSION%"
set KEY64="HKLM\SOFTWARE\WOW6432Node\JavaSoft\Java Runtime Environment\%JRE_VERSION%"
set VALUE=JavaHome
reg query %KEY% /v %VALUE% 2>nul || (
set KEY=!KEY64!
reg query !KEY! /v %VALUE% 2>nul || (
echo JavaHome not installed
exit /b 1
)
)
set JAVAHOME=
for /f "tokens=2,*" %%a in ('reg query %KEY% /v %VALUE% ^| findstr %VALUE%') do (
set JAVAHOME=%%b
)
echo JavaHome: %JAVAHOME%
endlocal

Categories