简体   繁体   中英

User preferences

I want to make a simple java program that creates a text file at somewhere. I want to let users choose the folder. But when I wrap it in jar file and send to others. Every time my friend runs it, it asks for the folder. I wonder how I can let the jar file only asks once and set it as final. Inside my .java file, I have something like

public void setDefaultFolder() {
    //initially path is empty string
    if(fc.getPath().equals("")){
        String a = JOptionPane.showInputDialog("Please select a default folder." +
                " Make sure it exists and it's not changeable once set");
        if(a != null) {
        String b = a.replace("\\","\\\\");
        // set String path = something users enter
        // fc is a helper object. I have all the read/write file or other methods 
        // there. I want to let the jar file read the path only for the first time
        // and set the path final, later on, when it detects path is not empty
        // string, it stops asking users to type in path.
        fc.setPath(b);
        }
        else {
            JOptionPane.showMessageDialog(null, "Folder not set");
        }
    }
} 

You need to save the users configuration somewhere. There is many ways to do this, for example you can use java.util.prefs package, as stated by Peter Knego in his answer to this question :

// Retrieve the user preference node for the package com.mycompany
Preferences prefs = Preferences.userNodeForPackage(com.mycompany.MyClass.class);

// Preference key name
final String PREF_NAME = "name_of_preference";

// Set the value of the preference
String newValue = "a string";
prefs.put(PREF_NAME, newValue);

// Get the value of the preference;
// default value is returned if the preference does not exist
String defaultValue = "default string";
String propertyValue = prefs.get(PREF_NAME, defaultValue); // "a string"

you might want to use a properties file to store the folder location. you would then load the property every time the jar loads

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