简体   繁体   中英

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 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?

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

public static void main(String[] args) {
    Module m = new Module();
    m.printOnDemand();

    Scanner sods = new Scanner(System.in);
    Path p = Paths.get("Z:\\DIS\\Project\\Data.txt");
    Path p1 = Paths.get("Data.txt");
    int count = p.getNameCount();

    System.out.println("file is :" + p.toString());
    System.out.println("file name P:" + p.getFileName());
    System.out.println("Names :" + p1.getFileSystem());
    System.out.println("There are :" + count + " elements in the path");


    for(int i = 0; i < count; i++)
    {
        System.out.println("Element :" + i + " is " + p.getName(i));

    }
} 

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM