What is the easiest way to make configuration files in Java?

Obviously, I want to avoid hard coding paths, etc. in my application, and as a result, I would like to create a settings file that will store simple things like strings, etc. What is the easiest way to do this? I was thinking about how Cocoa uses object persistence, but I cannot find anything equivalent.

+3
source share
7 answers

You can use properties files that are managed using java.util.Properties .

+10
source

Based on what you said the simplest:

, , . .

    // Save Settings
    Properties saveProps = new Properties();
    saveProps.setProperty("path1", "/somethingpath1");
    saveProps.setProperty("path2", "/somethingpath2");
    saveProps.storeToXML(new FileOutputStream("settings.xml"), "");

    // Load Settings
    Properties loadProps = new Properties();
    loadProps.loadFromXML(new FileInputStream("settings.xml"));
    String path1 = loadProps.getProperty("path1");
    String path2 = loadProps.getProperty("path2");
+8

, , , . (, PLIST ~/Library Mac OS X, gconf Gnome, Windows), java.util.prefs.Preferences - /. , Preferences , , , . , :

// 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();
// ...

, Preferences , . XML/*.properties , . XML , , , , , (, ), , , .. .

+3

. . - , Properties. . .

. , Resource . . .

+1

-, ( ) / .

, .

0

-, Spring 3.0. beans web.xml Dispatcher-servlet.xml.

, -, Jetty Tomcat, . , WAR.

, WAR.

0

? Serializable , .

, .

0

Source: https://habr.com/ru/post/1783124/


All Articles