问题
Is there a Java equivalent to .NET's App.Config?
If not is there a standard way to keep you application settings, so that they can be changed after an app has been distributed?
回答1:
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)
.
回答2:
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.
回答3:
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.
来源:https://stackoverflow.com/questions/212539/java-equivalent-to-app-config