Get the running JVM Path (Windows)Tag(s): Environment

We get the current PID (process identifier) and we launch a special VBScript to query process attached to the given PID.

Works only on Windows

import java.io.BufferedReader;
import java.io.File;
import java.io.FileWriter;
import java.io.InputStreamReader;

public class JVMUtils {

  public static long getPID() {
    String processName =
      java.lang.management.ManagementFactory.getRuntimeMXBean().getName();
    return Long.parseLong(processName.split("@")[0]);
  }

  public static String getJVMPath() {
    String path = "";
    try {
        File file = File.createTempFile("realhowto",".vbs");
        file.deleteOnExit();
        FileWriter fw = new java.io.FileWriter(file);

        String vbs = "Set WshShell = WScript.CreateObject(\"WScript.Shell\")\n"
               + "Set locator = CreateObject(\"WbemScripting.SWbemLocator\")\n"
               + "Set service = locator.ConnectServer()\n"
               + "Set processes = service.ExecQuery _\n"
               + " (\"select * from Win32_Process where ProcessId='"
               + JVMUtils.getPID() +"'\")\n"
               + "For Each process in processes\n"
               + "wscript.echo process.ExecutablePath \n"
               + "Next\n"
               + "Set WSHShell = Nothing\n";
        fw.write(vbs);
        fw.close();
        Process p =
            Runtime.getRuntime().exec("cscript //NoLogo " + file.getPath());
        BufferedReader input =
            new BufferedReader
              (new InputStreamReader(p.getInputStream()));
        path = input.readLine();
        input.close();
    }
    catch(Exception e){
        e.printStackTrace();
    }
    return path;
  }

  public static void main(String[] args) {
    System.out.println(JVMUtils.getJVMPath());
    /*
      output (example):
      C:\Program Files (x86)\Java\jre6\bin\javaw.exe
    */
 }
}

See also Determine if running from JAR, Get the "root" of an application and Obtain from where a Class is loaded




If you find this article useful, consider making a small donation
to show your support for this Web site and its content.

Written and compiled by Réal Gagnon ©1998-2012
[ home ]