为何需要Jython访问Java属性文件
使用Jython的过程中经常需要访问Java属性文件以得到配置信息。Jython 可以用loadProperties 和getProperty 函数做到这一点,如下所示:
def loadProperties (source):
""" 将Java属性文件加载入词典 """
result = {}
if type(source) == type(''): # name provided, use file
source = io.FileInputStream(source)
bis = io.BufferedInputStream(source)
props = util.Properties()
props.load(bis)
bis.close()
for key in props.keySet().iterator():
result[key] = props.get(key)
return result
def getProperty (properties, name, default=None):
""" 取得一个属性 """
return properties.get(name, default)
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.
- 11.
- 12.
- 13.
- 14.
- 15.
- 16.
Jython访问Java属性文件示例
所以,假如使用的是访问Java属性文件 中的函数,如下所示:
import sys
file = sys.argv[1]
props = loadProperties(file)
print "Properties file: %s, contents:" % file
print props
print "Property %s = %i" % ('debug', int(getProperty(props, 'debug', '0')))
import sys
file = sys.argv[1]
props = loadProperties(file)
print "Properties file: %s, contents:" % file
print props
print "Property %s = %i" % ('debug', int(getProperty(props, 'debug', '0')))
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.
- 11.
- 12.
- 13.
并且这些函数具有如下属性文件内容:
# 一个示例用属性文件
debug = 1
error.level = ERROR
now.is.the.time = false
# 一个示例用属性文件
debug = 1
error.level = ERROR
now.is.the.time = false
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
那么,得到的输出就会是:
Properties file: test.properties, contents:
{'error.level': 'ERROR', 'debug': '1', 'now.is.the.time': 'false'}
Property debug = 1
- 1.
- 2.
- 3.
以上就是Jython访问Java属性文件的实现方法。
【编辑推荐】