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
Written and compiled by Réal Gagnon ©1998-2012
[ home ]