Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect presence and location of JVM on Windows?

Tags:

java

windows

jvm

I'm trying to detect if there is a JVM installed and where it is located so I can run java.exe.

All I've managed to find is HKCU\Software\JavaSoft\Java Runtime Environment\<ver>. Is it safe to assume that it is installed in %PROGRAMFILES%\Java\jre<ver>?

I'm trying to do this in C#, but I assume the answer is pretty language agnostic, so any answer is appreciated.

EDIT: Ok silly me, I found How to detect whether java runtime is installed or not on a computer using c# which pointed me at HKLM\Software\JavaSoft\Java Runtime Environment\CurrentVersion which works with HKLM\Software\JavaSoft\Java Runtime Environment\<ver>\JavaHome. I managed to find these instead underneath HKLM\Software\Wow6432Node\JavaSoft\Java Runtime Environment. Is there some way to detect which of these I should be checking without trying to sniff at the CPU type?

like image 990
Matthew Scharley Avatar asked Jan 25 '11 09:01

Matthew Scharley


1 Answers

I'm going to throw my hat in the ring with the code I've ended up using:

string javaDirectory = null;

// Native registry key - 32b on 32b or 64b on 64b
// Fall back on 32b Java on Win64 if available
RegistryKey javaKey =
    Registry.LocalMachine.OpenSubKey("SOFTWARE\\Javasoft\\Java Runtime Environment") ??
    Registry.LocalMachine.OpenSubKey("SOFTWARE\\Wow6432Node\\Javasoft\\Java Runtime Environment");

if (javaKey != null)
{
    string javaVersion = javaKey.GetValue("CurrentVersion").ToString();
    try
    {
        javaDirectory = javaKey.OpenSubKey(javaVersion).GetValue("JavaHome").ToString();
    } catch(NullReferenceException)
    { /* Ignore null deref, means we can't get a directory */ }
}

if (javaDirectory == null)
{
    // deal with a lack of Java here.
}
like image 95
Matthew Scharley Avatar answered Sep 21 '22 08:09

Matthew Scharley