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?
The AppConfig class is a representation of the configuration of your Java application. You pass an AppConfig object into the security runtime instance when you initialize it. The AppConfig object is used to configure the security runtime based upon the configuration of your application.
Web. Config is used for asp.net web projects / web services. App. Config is used for Windows Forms, Windows Services, Console Apps and WPF applications.
config are only required, if you have coded your application in such a way that it is explicitly dependent on it. If you have not done this, or have put error handling/default values or actions in place where it can't read the config file, one would assume your application could run without it.
App. Config is an XML file that is used as a configuration file for your application. In other words, you store inside it any setting that you may want to change without having to change code (and recompiling). It is often used to store connection strings.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With