k0der k0der - 1 year ago 172
Java Question

How to get the full path of an executable in Java, if launched from Windows environment variable PATH?

I want to get the path of a executable launched in Java, if the executable is kept in a location which is part of Windows environment variable


Say for example, we launch
in windows using the below code snippet. Here
is kept under
folder which is a part of the Windows environment variable
. So no need to give the complete path of the executable here.

Runtime runtime = Runtime.getRuntime();
Process process = runtime.exec("notepad.exe");

So my question is, how to get the absolute location of the executables/files in Java programs (in this case if
is kept under
, inside java program I need to get path
), if they are launched like this from

Answer Source

They're is no built-in function to do this. But you can find it the same way the shell finds executables on PATH.

Split the value of the PATH variable, iterate over the entries, which should be directories, and the first one that contains notepad.exe is the executable that was used.

public static String findExecutableOnPath(String name) {
    for (String dirname : System.getEnv("PATH").split(File.pathSeparator)) {
        File file = new File(dirname, name);
        if (file.isFile() && file.canExecute()) {
            return file.getAbsolutePath();
    throw new AssertionError("should have found the executable");

I don't have a compiler with me now to verify, but I think the above will work.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download