Avg. Rating 4.5

Problem

You have one or more standard properties files that you'd like to load into a ColdFusion struct.

Solution

We can leverage Java's java.util.Properties to quickly load properties files.

Detailed explanation

ColdFusion certainly makes it easy to parse through a properties file "manually" with cffile and some simple list functions, however, the Java class java.util.Properties already does the work of loading a properties file. It can accept various forms as specified by the class' load(Reader) .

For the following example, let's say you have a file called properties.ini that contains the following:

# App properties
prop1 = value1
prop2 = value2
prop3 = value 3

Here's a simple example to show how we load these properties into a java.util.Properties object and then get a property:

file = expandPath( './properties.ini' );
properties = createObject( 'java', 'java.util.Properties' ).init();
fileStream = createObject( 'java', 'java.io.FileInputStream'
).init( file );
properties.load( fileStream );
writeOutput( 'property1 is ' & properties.getProperty( 'prop1'
) );

It is then very simple to create a ColdFusion Component (CFC) that will abstract and encapsulate this little bit of Java work for you, and also allow you to pass a list of properties files to the init() method (allowing you to load multiple properties files into one properties object in just one line of code!).

The attached folder contains a Properties.cfc file, which will allow you to load files as follows:

files = 'sample1.properties,sample2.properties,sample3.properties';
properties = createObject( 'component', 'Properties' ).init( files
);
writeOutput( 'key1 is ' & properties.getProperty( 'key1' ) );

The attached folder also contains an example.cfm template, with some sample usage code, and three sample properties files.

I should also note that the built-in ColdFusion function getProfileString() is relevant here, however, I just don't like having to pass an absolute file path to this function every time you want to retrieve a single property value. I'd also imagine that there's a slight performance hit if you reference this function frequently (guessing it must parse through the INI file each time, to find the section/property requested).

properties.zip
[example.cfm to demo usage of Properties.cfc, plus three sample properties files.]

+
This work is licensed under a Creative Commons Attribution-Noncommercial-Share Alike 3.0 Unported License. Permissions beyond the scope of this license, pertaining to the examples of code included within this work are available at Adobe.

Report abuse

Related recipes