如何在Windows上的Java应用程序中设置/更新PATH变量?

时间:2011-12-02 01:23:44

标签: java windows path

与此命令行等效的内容:

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

要运行我的应用程序,有些东西必须在PATH变量中。所以我想在程序开始时捕获异常,如果程序无法启动并显示一些向导供用户选择需要在PATH中的程序的安装文件夹。我会把该文件夹的绝对路径添加到PATH变量并再次启动我的应用程序。

修改

那"某事"是VLC播放器。我需要它在PATH变量中的安装文件夹(例如:C:\ Program Files \ VideoLAN \ VLC)。我的应用程序是单个可执行.jar文件,为了使用它,VLC需要在PATH中。因此,当用户首次启动我的应用程序时,会弹出该小向导以选择VLC文件夹,然后我会用它更新PATH。

1 个答案:

答案 0 :(得分:3)

您可以使用Process对象执行命令,也可以使用BufferedReader读取其输出,这是一个可以帮助您的简单示例:

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");
    }
}
相关问题