Creating Java config files

Viewed 35

What exactly is the best way to generate config files for my Java application? Right now I have a runnable jar which when opened will open a file selector gui for the user to select where the config files along with saved data should be stored at. I have my default config file saved in my resource folder and I am wanting to save that file to the location specified. Anyways the problem I am having is that I am not sure how I will be able to refence back to those files in the future because I only want that file selector to pop up once. As soon as the application is closed all references to that file pathway would be lost. The only thing I can think of is that I could replace my config.yml file inside the resource folder with the newly generated file and include a file location parameter (if that is even possible). But to be honest I am not sure how programs actually handle this and would love any insight into this topic.

1 Answers

Perhaps place the selected path into a small text file located within the Startup directory of your JAR file. Encrypt it if you like or whatever. The method below should provide you with the Directory (folder) path of where your JAR file was started:

/**
 * Returns the path from where the JAR file was started. In other words, the
 * installed JAR file's home directory (folder).<br><br>
 * 
 * <b>Example Usage:</b><pre>
 *   <code>String applicationPath = appPath(MyStartupClassName.class);</code></pre>
 *
 * @param mainStartupClassName (Class) The main startup class for your
 *                             particular Java application. To be supplied
 *                             as: <b>MyMainClass.class</b><br>
 *
 * @return (String) The full path to where the JAR file resides (its Home
 *         Directory).
 */
public static String appPath(Class<?> mainStartupClassName) {
    try {
        String path = mainStartupClassName.getProtectionDomain().getCodeSource().getLocation().getPath();
        String pathDecoded = java.net.URLDecoder.decode(path, "UTF-8");
        pathDecoded = pathDecoded.trim().replace("/", File.separator);
        if (pathDecoded.startsWith(File.separator)) {
            pathDecoded = pathDecoded.substring(1);
        }
        return pathDecoded.substring(0, pathDecoded.lastIndexOf(File.separator));
    }
    catch (java.io.UnsupportedEncodingException ex) {
        java.util.logging.Logger.getLogger("appPath()")
                .log(java.util.logging.Level.SEVERE, null, ex);
    }
    return null;
}
Related