将字符串解析为属性

我正在从数据库中读取属性文件。 我检查了java.util.Properties并且没有从String实例解析的方法。 有什么办法吗?

你是对的java.util.Properties没有从String读取的方法 – 但实际上它有更多通用方法从InputStreamReader

因此,如果您有某种方式将String呈现为其中任何一种,即可以逐个有效地迭代字符的源,则可以调用load 。 这感觉它应该存在,事实上它确实存在 – java.io.StringReader 。

那么,把它放在一起非常简单:

 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; } 

我使用此代码从单个DB列加载属性

 public Properties buildProperties(String propertiesFromString, String entrySeparator) throws IOException { Properties properties = new Properties(); properties.load(new StringReader(propertiesFromString.replaceAll(entrySeparator, "\n"))); return properties; } 

通过简单的测试

 @Test public void testProperties() throws Exception { Properties properties = buildProperties("A=1;B=2;Z=x",";"); assertEquals("1", properties.getProperty("A")); assertEquals("2", properties.getProperty("B")); assertEquals("3", properties.getProperty("C","3")); assertNull(properties.getProperty("Y")); assertEquals("x", properties.getProperty("Z")); } 

我们遇到了类似的问题,上面的内容对我们没有用。

但是,下面的确如此。

 def content = readFile 'gradle.properties' Properties properties = new Properties() InputStream is = new ByteArrayInputStream(content.getBytes()); properties.load(is) def runtimeString = 'SERVICE_VERSION_MINOR' echo properties."$runtimeString" SERVICE_VERSION_MINOR = properties."$runtimeString" echo SERVICE_VERSION_MINOR