Saturday, January 15, 2011

jython and java.util.Properties

The other day my boss gave me an assignment to create a static properties file with stringified numeric mappings of file lookups.  Turns out this is really easy in jython (if you're used to Python instead of Java).  Hardly any Java is required:

$ /usr/local/jdk-1.7.0/bin/java -jar jython.jar
Jython 2.5.1 (Release_2_5_1:6813, Sep 26 2009, 13:47:54)
[OpenJDK Client VM (Sun Microsystems Inc.)] on java1.7.0-internal
Type "help", "copyright", "credits" or "license" for more information.
>>> from java.util import Properties
>>> filemappings = {'1':'',
...                 '2':'',
...                 '3':''}
>>> props = Properties()
>>> for key in filemappings:
...     props.setProperty(key, filemappings[key])
>>> fle = open('blah', 'w')
>>>, 'put comment here')
>>> fle.close()
>>> fle = open('blah', 'r')
>>> props = Properties()
>>> props.load(fle)
>>> props.getProperty('1')
>>> for prop in props:
...     print prop, props.getProperty(prop)
>>> fle.close()

The file itself looks like this:

#put comment here
#Sat Jan 15 16:24:57 MST 2011

The value strings are stored in a manner that has them returned as Jython Unicode strings.
My case is the simplest one, in that the properties file is static.  To update it dynamically and store it for the next use (for example, to maintain state), you would need a writable file object.