Configuration files are used in applications to store settings, user preferences and other configuration parameters of an application so that. When configurations are changed from within the application these need to be saved so that next time the application starts with these new settings.
In Java reading and writing to a configuration is pretty simple and straight forward.
A configuration file can store data in many ways. One simple technique is :
key=value
Apart from this XML can also be used to save parameters.
The following two methods should serve the purpose of reading and saving configurations :
//Writing and Saving Configurations private void setPreference(String Key, String Value) { Properties configFile = new Properties(); try { InputStream f = new FileInputStream("configuration.xml"); configFile.loadFromXML(f); f.close(); } catch(IOException e) { } catch(Exception e) { JOptionPane.showMessageDialog(null, e.getMessage()); } configFile.setProperty(Key, Value); try { OutputStream f = new FileOutputStream("configuration.xml"); configFile.storeToXML(f,"Configuration file for the Profit System"); } catch(Exception e) { } } //Reading Configurations private static String getPreference(String Key) { Properties configFile = new Properties(); try { InputStream f = new FileInputStream("configuration.xml"); configFile.loadFromXML(f); f.close(); } catch(IOException e) { } catch(Exception e) { JOptionPane.showMessageDialog(null , e.getMessage()); } return (configFile.getProperty(Key)); }
Instead the storeFromXML and loadFromXML store and load methods can be used to simply store the data in the key=value format instead of xml format.