2009-10-23 96 views
2

我从C#代码调用javac。最初,我发现它的位置仅如下:如何以编程方式查找javac.exe?

protected static string JavaHome 
{ 
    get 
    { 
     return Environment.GetEnvironmentVariable("JAVA_HOME"); 
    } 
} 

然而,我刚安装了JDK在新电脑上,发现它没有自动设置JAVA_HOME环境变量。 需要的环境变量是在任何Windows应用程序在过去十年中不能接受的,所以我需要一种方法来寻找javac如果JAVA_HOME环境变量未设置:

protected static string JavaHome 
{ 
    get 
    { 
     string home = Environment.GetEnvironmentVariable("JAVA_HOME"); 
     if (string.IsNullOrEmpty(home) || !Directory.Exists(home)) 
     { 
      // TODO: find the JDK home directory some other way. 
     } 

     return home; 
    } 
} 
+3

为什么不能接受?计算机应该如何神奇地知道可执行文件的安装位置?他们不是介意读者,他们是电脑,你必须告诉他们该怎么做...... – amischiefr 2009-10-23 17:48:31

+0

因为他们没有在环境中正确同步,他们是一个配置的痛苦,我厌倦了写作令人费解的指示给用户。 – 2009-10-23 17:51:14

回答

4

如果您使用的是Windows,使用注册表:

HKEY_LOCAL_MACHINE \ SOFTWARE \ JavaSoft的\ Java开发工具包

如果你没有,你几乎套牢ENV变量。您可能会发现this博客条目很有用。

通过280Z28编辑:

在其下方的注册表项是一个CURRENTVERSION值。该值是用来寻找Java主在以下位置:
HKEY_LOCAL_MACHINE\SOFTWARE\JavaSoft\Java Development Kit\{CurrentVersion}\JavaHome

private static string javaHome; 

protected static string JavaHome 
{ 
    get 
    { 
     string home = javaHome; 
     if (home == null) 
     { 
      home = Environment.GetEnvironmentVariable("JAVA_HOME"); 
      if (string.IsNullOrEmpty(home) || !Directory.Exists(home)) 
      { 
       home = CheckForJavaHome(Registry.CurrentUser); 
       if (home == null) 
        home = CheckForJavaHome(Registry.LocalMachine); 
      } 

      if (home != null && !Directory.Exists(home)) 
       home = null; 

      javaHome = home; 
     } 

     return home; 
    } 
} 

protected static string CheckForJavaHome(RegistryKey key) 
{ 
    using (RegistryKey subkey = key.OpenSubKey(@"SOFTWARE\JavaSoft\Java Development Kit")) 
    { 
     if (subkey == null) 
      return null; 

     object value = subkey.GetValue("CurrentVersion", null, RegistryValueOptions.None); 
     if (value != null) 
     { 
      using (RegistryKey currentHomeKey = subkey.OpenSubKey(value.ToString())) 
      { 
       if (currentHomeKey == null) 
        return null; 

       value = currentHomeKey.GetValue("JavaHome", null, RegistryValueOptions.None); 
       if (value != null) 
        return value.ToString(); 
      } 
     } 
    } 

    return null; 
} 
+0

对于Linux用户,我已经遇到了这个代码示例,它也做了同样的事情:http://agiletrack.net/samples/sample-detect-java.html – luvieere 2009-10-23 17:59:20

+0

agiletrack.net url not working,please post how to检测linuc中的java_home – Udhaya 2016-06-13 10:06:52

1

你或许应该在注册表中搜索一个JDK安装地址。

作为替代,请参阅this讨论。

0

对于64位操作系统(Windows 7),该注册表项可能是下

HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\JavaSoft\Java Development Kit

如果你正在运行一个32位的JDK。所以,如果你已经根据上面的代码编写了代码,那么再次测试。

我还没有完全掌握Microsoft registry redirection/reflection的东西。

相关问题