将字符串解析为属性

时间:2012-03-12 18:01:35

标签: java

我正在从数据库中读取属性文件。 我检查了java.util.Properties,并且没有方法可以从String实例进行解析。有没有办法做到这一点?

4 个答案:

答案 0 :(得分:75)

你是对的java.util.Properties没有方法可以从String读取 - 但实际上它有更通用的方法可以从InputStream或{{1 }}

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

然后,把它放在一起非常简单:

String

答案 1 :(得分:1)

我使用此代码从单个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"));  
}

答案 2 :(得分:0)

我们遇到了类似的问题,上述内容对我们无效。

然而,下面的确如此。

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

答案 3 :(得分:0)

这两个实用程序方法可以通过java.util.Properties对象向String写入和读取:

/**
 * Converts a {@link Properties} object to {@link String} and you can
 * also provide a description for the output.
 *
 * @param props an input {@link Properties} to be converted to {@link String}
 * @param desc  an input description for the output
 * @return an output String that could easily parse back to {@link Properties} object
 * @throws IOException If writing encounter a problem or if an I/O error occurs.
 */
private static String convert2String(final Properties props, String desc) throws IOException {
    final StringWriter sw = new StringWriter();
    String propStr;
    try {
        props.store(sw, desc);
        propStr = sw.toString();
    } finally {
        if (sw != null) {
            sw.close();
        }
    }

    return propStr;
}


/**
 * Converts {@link String} to {@link Properties}
 * @param propsStr an {@link String} input that is saved via convert2String method
 * @return a {@link Properties} object
 * @throws IOException if an error occurred when reading from the {@link StringReader}
 */
private static Properties convert2Properties(final String propsStr) throws IOException {
    final Properties props = new Properties();
    final StringReader sr = new StringReader(propsStr);
    try {
        props.load(sr);
    } finally {
        if (sr != null)
            sr.close();
    }

    return props;
}
  

我发现以上两种方法在有很多属性时很有用   并且您想将所有这些都保存在storage or database中,并且您不想创建一个庞大的key-value存储表。