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':'numberone.py',
...                 '2':'numbertwo.py',
...                 '3':'numberthree.py'}
>>> props = Properties()
>>> for key in filemappings:
...     props.setProperty(key, filemappings[key])
...
>>> fle = open('blah', 'w')
>>> props.store(fle, 'put comment here')
>>> fle.close()
>>> fle = open('blah', 'r')
>>> props = Properties()
>>> props.load(fle)
>>> props.getProperty('1')
u'numberone.py'
>>> for prop in props:
...     print prop, props.getProperty(prop)
...
3 numberthree.py
2 numbertwo.py
1 numberone.py
>>> fle.close()
>>>





The file itself looks like this:



#put comment here
#Sat Jan 15 16:24:57 MST 2011
3=numberthree.py
2=numbertwo.py
1=numberone.py


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.