k0der k0der - 3 months ago 20
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

PATH
.

Say for example, we launch
NOTEPAD
in windows using the below code snippet. Here
notepad.exe
is kept under
Windows
folder which is a part of the Windows environment variable
PATH
. 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
notepad.exe
is kept under
c:\windows
, inside java program I need to get path
c:\windows
), if they are launched like this from
PATH
locations?

Answer

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.