将字符串解析为属性 [英] Parsing string as properties
问题描述
我正在从数据库中读取属性文件。
我检查了 java.util.Properties
,并且没有从 String
实例解析的方法。有没有办法做到这一点?
I am reading a properties file from database.
I checked java.util.Properties
and there's no method to parse from a String
instance. Is there any way to do it?
推荐答案
你是对的 java.util.Properties
没有从 String
读取的方法 - 但事实上它有更多通用方法从读取InputStream
或读者
。
You're right that java.util.Properties
doesn't have a method to read from a String
- but in fact it has more general methods that read from an InputStream
or Reader
.
所以你可以打电话给 loading
如果你有某种方式将 String
作为其中任何一个呈现,即一个有效地逐个遍历字符的源。这感觉它应该存在,事实确实如此 - java.io.StringReader 。
So you can call load
if you have some way of presenting your String
as either of these, i.e. a source which effectively iterates over characters one by one. This feels like it ought to exist, and indeed it does - java.io.StringReader.
然后把它放在一起非常简单:
Putting it together, then, is quite straightforward:
public Properties parsePropertiesString(String s) {
// grr at load() returning void rather than the Properties object
// so this takes 3 lines instead of "return new Properties().load(...);"
final Properties p = new Properties();
p.load(new StringReader(s));
return p;
}
这篇关于将字符串解析为属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!