Find absolute java.exe path programmatically from java code

后端 未结 3 708
面向向阳花
面向向阳花 2020-11-29 09:35

If I have a java jar or class file which is launched by the user (assuming java path is set in environment variables), so how can i from within the code, figure out absolute

3条回答
  •  [愿得一人]
    2020-11-29 10:03

    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.

提交回复
热议问题