I want to get the path of an 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?
Open a Command Prompt window (Win⊞ + R, type cmd, hit Enter). Enter the command echo %JAVA_HOME% . This should output the path to your Java installation folder. If it doesn't, your JAVA_HOME variable was not set correctly.
Right-click the “Start” menu shortcut for the application, and select More > Open file location. This will open a File Explorer window that points to the actual application shortcut file. Right click on that shortcut, and select “Properties.” No matter how you located the shortcut, a properties window will appear.
In Java, for NIO Path, we can use path. toAbsolutePath() to get the file path; For legacy IO File, we can use file. getAbsolutePath() to get the file path.
There 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");
}
You can get the location of an executable in Windows by:
where <executable_name>
For example:
where mspaint
returns:
C:\Windows\System32\mspaint.exe
And the following code:
Process process = Runtime.getRuntime().exec("where notepad.exe");
try (BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream()))) {
File exePath = new File(in.readLine());
System.out.println(exePath.getParent());
}
Will output:
C:\Windows\System32
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With