What is the simplest way to do settings files in Java?

前端 未结 8 1475
清歌不尽
清歌不尽 2021-01-03 05:47

Obviously enough, I want to avoid hardcoding paths and such into my application, and as a result, I\'d like to make a settings file that will store simple things like string

8条回答
  •  时光说笑
    2021-01-03 06:21

    This depends on how you want your application to be configured and who you expect will configure the application. If you want to use the system's native configuration mechanism (e.g. PLIST files in ~/Library on Mac OS X, gconf on Gnome, the system registry on Windows), then java.util.prefs.Preferences is the correct and simple way to deal with settings / preferences. You would still probably want to create your own class on top of Preferences with named constants for the keys as well as the default values for these settings, and possibly helper methods to retrieve them. Here is an example of how to use it:

    // Class to wrap some settings
    public class AnimationSettings {
        private static final String VELOCITY_KEY = "velocity";
        private static final double VELOCITY_DEFAULT = 5.0;
    
        public static double getVelocity() {
            return getPrefs().getDouble(VELOCITY_KEY, VELOCITY_DEFAULT);
        }
    
        public static void setVelocity(int velocity) {
             getPrefs().putDouble(VELOCITY_KEY, velocity);
        }
    
        public static void sync() {
             getPrefs().sync();
        }
    
        private static Preferences getPrefs() {
            if (preferences_ == null) {
               preferences_ = Preferences.userNodeForPackage(AnimationSettings.class);
            }
            return preferences_;
        }
    
        private static Preferences preferences_ = null;
    };
    
    // Elsewhere in the application:
    //...
    double velocity = AnimationSettings.getVelocity();
    // ...
    

    That said, the Preferences class will not give you a single way to configure your application across platforms, and it doesn't necessarily give you a configuration file. For that, XML / *.properties files are also a possible solution as suggested by some of the other answerers. A downside to using XML and properties files, however, is that you must then deal with where they should go, how you would look them up, whether you want to have multiple such files one overriding the other (e.g. system settings and user settings), what to do if the file isn't there, etc. Preferences nicely handles these sorts of things.

提交回复
热议问题