Jython訪問Java屬性文件的方法一覽
作者:佚名
本文介紹了Jython訪問Java屬性文件的方法。在Jython中可以通過loadProperties 和getProperty 函數(shù)做到這一點(diǎn)。
為何需要Jython訪問Java屬性文件
使用Jython的過程中經(jīng)常需要訪問Java屬性文件以得到配置信息。Jython 可以用loadProperties 和getProperty 函數(shù)做到這一點(diǎn),如下所示:
- 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)
Jython訪問Java屬性文件示例
所以,假如使用的是訪問Java屬性文件 中的函數(shù),如下所示:
- 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')))
并且這些函數(shù)具有如下屬性文件內(nèi)容:
- # 一個示例用屬性文件
- debug = 1
- error.level = ERROR
- now.is.the.time = false
- # 一個示例用屬性文件
- debug = 1
- error.level = ERROR
- now.is.the.time = false
那么,得到的輸出就會是:
- Properties file: test.properties, contents:
- {'error.level': 'ERROR', 'debug': '1', 'now.is.the.time': 'false'}
- Property debug = 1
以上就是Jython訪問Java屬性文件的實(shí)現(xiàn)方法。
【編輯推薦】
責(zé)任編輯:yangsai
來源:
網(wǎng)絡(luò)