Java中使用参数选择 – Use Preferences in Java

Categories: Java; Tagged with: ; @ February 1st, 2009 0:30

API: http://gceclub.sun.com.cn/Java_Docs/html/zh_CN/api/java/util/prefs/Preferences.html

需求: 某文件解析器, 设定解析的默认文件, 在关闭时将最后一次解析的路径保存, 再次打开时, 取出上次解析文件之路径.

用法:

取得针对此包的用户和系统参数选择的Preferences对象:

private Preferences userPrefs = Preferences.userNodeForPackage(SwingUI.class);
private Preferences sysPrefs = Preferences.systemNodeForPackage(SwingUI.class);

查询参数选择值[默认值]:

public void initPrefs() {
    filePath = userPrefs.get("filePath", http://liguoliang.com/email.txt);
}

关闭之前保存最后一次解析文件的路径:

监听关闭事件:

        /**//* 使用匿名类添加一个窗口监听器 */
        addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {
            	savePrefs();
            	System.out.println(
                    "Exit when Closed event");
                //退出应用程序
                System.exit(0);
            }
        });

保存数据

public void savePrefs() {
    userPrefs.put("filePath", textFilePath.getText());
    try {
        userPrefs.flush();
    } catch (BackingStoreException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

如图: 第一次运行时, 默认路径: http://liguoliang.com/email.txt

image

在File中输入: http://xjst.org
image

点击关闭程序, 再次运行:

image

此时默认路径为上一次解析的http://xjst.org/

<->



// Proudly powered by Apache, PHP, MySQL, WordPress, Bootstrap, etc,.