簡體   English   中英

如何以編程方式找到javac.exe?

[英]How do I find javac.exe programmatically?

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

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

HKEY_LOCAL_MACHINE \\ SOFTWARE \\ JavaSoft \\ Java開發工具包

如果不是這樣,那么您就很容易陷入環境變量中。 您可能會發現博客條目很有用。

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

您可能應該在注冊表中搜索JDK安裝地址。

或者,請參閱討論。

對於64位操作系統(Windows 7),注冊表項可能位於

HKEY_LOCAL_MACHINE\\SOFTWARE\\Wow6432Node\\JavaSoft\\Java Development Kit

如果您正在運行32位JDK。 因此,如果您都已根據上述內容編寫了代碼,請再次進行測試。

我還沒有完全了解Microsoft注冊表重定向/反射的內容。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM