如何以编程方式查找javac.exe?
问题描述:
我从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;
}
}
答
如果您使用的是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;
}
答
对于64位操作系统(Windows 7),该注册表项可能是下
HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\JavaSoft\Java Development Kit
如果你正在运行一个32位的JDK。所以,如果你已经根据上面的代码编写了代码,那么再次测试。
我还没有完全掌握Microsoft registry redirection/reflection的东西。
为什么不能接受?计算机应该如何神奇地知道可执行文件的安装位置?他们不是介意读者,他们是电脑,你必须告诉他们该怎么做...... – amischiefr 2009-10-23 17:48:31
因为他们没有在环境中正确同步,他们是一个配置的痛苦,我厌倦了写作令人费解的指示给用户。 – 2009-10-23 17:51:14