【问题标题】:How do I find javac.exe programmatically?如何以编程方式找到 javac.exe?
【发布时间】:2010-12-09 13:18:49
【问题描述】:

我从 C# 代码调用 javac。原来我只找到它的位置如下:

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

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

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;
    }
}

【问题讨论】:

  • 为什么不能接受?计算机应该如何神奇地知道可执行文件的安装位置?他们不是读心者,他们是计算机,你必须告诉他们该做什么......
  • 因为它们没有在整个环境中正确同步,所以配置起来很麻烦,而且我厌倦了必须向用户编写复杂的指令。

标签: .net environment-variables java javac


【解决方案1】:

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

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

如果你不是,你几乎被环境变量困住了。您可能会发现 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;
}

【讨论】:

【解决方案2】:

您可能应该在注册表中搜索 JDK 安装地址。

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

【讨论】:

    【解决方案3】:

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

    HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\JavaSoft\Java Development Kit

    如果您运行的是 32 位 JDK。因此,如果您都根据上述编写了代码,请再次进行测试。

    我还没有完全理解 Microsoft registry redirection/reflection 的东西。

    【讨论】:

      猜你喜欢
      • 2014-08-22
      • 2015-05-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多