Java equivalent to app.config?

六眼飞鱼酱① 提交于 2019-12-02 23:47:28

For WebApps, web.xml can be used to store application settings.

Other than that, you can use the Properties class to read and write properties files.

You may also want to look at the Preferences class, which is used to read and write system and user preferences. It's an abstract class, but you can get appropriate objects using the userNodeForPackage(ClassName.class) and systemNodeForPackage(ClassName.class).

To put @Powerlord's suggestion (+1) of using the Properties class into example code:

public class SomeClass {
    public static void main(String[] args){
        String dbUrl = "";
        String dbLogin = "";
        String dbPassword = "";     
        if (args.length<3) {
            //If no inputs passed in, look for a configuration file
            URL configFile = SomeClass.class.getClass().getResource("/Configuration.cnf");
            try {
                InputStream configFileStream = configFile.openStream();
                Properties p = new Properties();
                p.load(configFileStream);
                configFileStream.close();

                dbUrl      = (String)p.get("dbUrl");
                dbLogin    = (String)p.get("dbUser");
                dbPassword = (String)p.get("dbPassword");               
            } catch (Exception e) {  //IO or NullPointer exceptions possible in block above
                System.out.println("Useful message");
                System.exit(1);
            }
        } else {
            //Read required inputs from "args"
            dbUrl      = args[0];
            dbLogin    = args[1];
            dbPassword = args[2];           
        }
        //Input checking one three items here
        //Real work here.
    }
}

Then, at the root of the container (e.g. top of a jar file) place a file Configuration.cnf with the following content:

#Comments describing the file
#more comments
dbUser=username
dbPassword=password
dbUrl=jdbc\:mysql\://servername/databasename

This feel not perfect (I'd be interested to hear improvements) but good enough for my current needs.

The simple way is to simply have a properties file, e.g., myapp.properties, with all your settings in. It's not a very advanced way to do settings but it suffices, or you can have your own XML based setup, or get them from a database, etc.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!