AdobeStock_455007340

Reading Java Properties Files

Windows users are familiar with .ini files, those plain text files that are really useful for storing configuration data and things like that. Java has a similar type of file, a properties file (usually with a .properties extension), and a set of APIs (rather ugly APIs, actually, in java.util.Properties) that are used for reading and writing these files. The format of .properties files is very simple; entries are stored one per line in name=value pairs, lines beginning with # are comments, blank lines are ignored, and .ini type sections are not supported. A simple .properties file may contain:
#comment
#last modified date
item1=value1
item2=value2
...

I’ve been using .properties files in a few recent projects and found myself needing to access them from within ColdFusion code. CFML has built-in functions for accessing .ini files, but none for .properties files. After spending way too much time trying to invoke the Java APIs from within ColdFusion I realized that a simple ColdFusion UDF could make the job a whole lot easier. So, here is my ReadProperties() function, pass it a complete path to a .properties file, and it will return a standard ColdFusion structure containing all the name=value pairs.






























So far this UDF has been able to handle any .properties file I threw at it. I know that I may still need to use the native Java APIs at some point, but for now, this works really well, and is actually much more pleasant to use than Java’s own APIs.

2 responses to “Reading Java Properties Files”

  1. Matt Liotta Avatar
    Matt Liotta

    Here is an example of how to use the Java API instead.
    <cfscript>
    fis = CreateObject("java", "java.io.FileInputStream");
    fis.init("path to properties file here");
    properties = CreateObject("java", "java.util.Properties");
    properties.load(fis);
    </cfscript>
    <cfoutput>#properties.get("some key")#</cfoutput>

  2. James Ang Avatar
    James Ang

    Matt’s way is probably best. 😛
    That said, you should use ListRest() as opposed to ListLast(). This way you take care of the pathological case when there are more than one ‘=’ on one line.
    Mind you, I am no expert on .properties file. Maybe multiple ‘=’ signs are not allowed per line! 😛

Leave a Reply