javawindowspath

How can I set/update the PATH variable from within a Java application on Windows?


Something equivalent to this command line:

set PATH=%PATH%;C:\Something\bin

To run my application, something has to be in a PATH variable. So I want at the program beginning catch exceptions if the program fails to start and display some wizard for the user to select the installation folder of a program that needs to be in a PATH. Then I would take that folder's absolute path and add it to the PATH variable and start my application again.

That "something" is VLC media player. I need its installation folder in the PATH variable (for example: C:\Program Files\VideoLAN\VLC). My application is a single executable .jar file and in order to use it, VLC needs to be in a PATH. So when the user first starts my application, that little wizard would pop up to select the VLC folder, and then I would update PATH with it.


Solution

  • You can execute commands using the Process object, and you can also read the output of that using a BufferedReader. Here's a quick example that may help you out:

    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStreamReader;
    
    public class Main {
    
        public static void main(String args[]) {
            try {
                Process proc = Runtime.getRuntime().exec("cmd set PATH=%PATH%;C:\\Something\\bin");
                proc.waitFor();
                BufferedReader reader = new BufferedReader(new InputStreamReader(proc.getInputStream()));
    
                String line = reader.readLine();
                while (line != null) {
                    // Handle what you want it to do here
                    line = reader.readLine();
                }
            }
            catch (IOException e1) {
                // Handle your exception here
            }
            catch(InterruptedException e2) {
                // Handle your exception here
            }
    
            System.out.println("Path has been changed");
        }
    }