Find absolute java.exe path programmatically from java code

北城以北 提交于 2019-11-27 02:04:29
String javaHome = System.getProperty("java.home");

Can you tell me either through pure Java ... on windows how is it possible to find out the location of javaw.exe?

E.G.

import java.io.File;

class JavawLocation {

    public static void main(String[] args) {
        String javaHome = System.getProperty("java.home");
        File f = new File(javaHome);
        f = new File(f, "bin");
        f = new File(f, "javaw.exe");
        System.out.println(f + "    exists: " + f.exists());
    }
}

Output

C:\Program Files (x86)\Java\jdk1.6.0_29\jre\bin\javaw.exe    exists: true
Press any key to continue . . .

And yes, I am confident that will work in a JRE.

Greg

On Windows, the java.library.path System Property begins with the path to the bin directory containing whichever java.exe was used to run your jar file.

This makes sense, because on Windows the first place any executable looks for DLL files is the directory containing the executable itself. So naturally, when the JVM runs, the first place it looks for DLLs is the directory containing java.exe.

You can acquire the path to java.exe as follows:

final String javaLibraryPath = System.getProperty("java.library.path");
final File javaExeFile = new File(
  javaLibraryPath.substring(0, javaLibraryPath.indexOf(';')) + "\\java.exe"
);
final String javaExePath =
  javaExeFile.exists() ? javaExeFile.getAbsolutePath() : "java";

This code is Windows-specific - I hard-coded the path separator (;) and the file separator (). I also put in a fallback to just "java" in case the library path trick somehow doesn't work.

I have tested this with Java 6 and 7 on Windows 7. I tried a 32-bit and 64-bit version of Java.

Here's a slightly more generalised solution that I came up with. Maybe useful:

private static String javaExe()
{
    final String JAVA_HOME = System.getProperty("java.home");
    final File BIN = new File(JAVA_HOME, "bin");
    File exe = new File(BIN, "java");

    if (!exe.exists())
    {
        // We might be on Windows, which needs an exe extension
        exe = new File(BIN, "java.exe");
    }

    if (exe.exists())
    {
        return exe.getAbsolutePath();
    }

    try
    {
        // Just try invoking java from the system path; this of course
        // assumes "java[.exe]" is /actually/ Java
        final String NAKED_JAVA = "java";
        new ProcessBuilder(NAKED_JAVA).start();

        return NAKED_JAVA;
    }
    catch (IOException e)
    {
        return null;
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!