A properties file in Java can be very useful when you start to notice that there are many locations in your code where you are either hard coding values, many constants, or using enums. Instead of including these values directly in your code, you can refactor them out to a properties file to separate responsibilities. Instead of potentially specifying values throughout many classes or programs, all values can be condensed into one or more properties files as need.
An example of a properties file is as follows:
# a comment ! a comment a = a string b = a string with escape sequences \t \n \r \\ \" \' \ (space) \u0123 c = a string with a continuation line \ continuation line d.e.f = another string
A properties file can be read or conversely written as follows:
// Read properties file. Properties properties = new Properties(); try { properties.load(new FileInputStream("filename.properties")); } catch (IOException e) { } // Write properties file. try { properties.store(new FileOutputStream("filename.properties"), null); } catch (IOException e) { }
Setting or retrieving values from an existing properties file can be performed as follows:
String string = properties.getProperty("a.b"); properties.setProperty("a.b", "new value");
That's it! Properties files are easy to create and work with and can greatly aid in organizing and cleaning up your code.





Comments
RSS feed for comments to this post