Java 将字符串解析为属性

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9672327/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-16 05:57:22  来源:igfitidea点击:

Parsing string as properties

java

提问by lucky_start_izumi

I am reading a properties file from database. I checked java.util.Propertiesand there's no method to parse from a Stringinstance. Is there any way to do it?

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

采纳答案by Andrzej Doyle

You're right that java.util.Propertiesdoesn't have a method to read from a String- but in fact it has more general methods that read from an InputStreamor Reader.

你是对的,java.util.Properties没有从 a 读取的方法String- 但实际上它有更通用的方法可以从InputStreamor读取Reader

So you can call loadif you have some way of presenting your Stringas 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.

因此,load如果您有某种方式将您的内容呈现String为其中任何一种,即一个有效地逐个迭代字符的源,则可以调用。这感觉它应该存在,而且确实存在 - 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;
}

回答by user3265317

We had a similar problem, the above did not work for us.

我们遇到了类似的问题,上述方法对我们不起作用。

The below, however, did.

然而,下面做到了。

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

回答by alfiogang

I use this code to load properties from a single DB column

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

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

with a simple test

用一个简单的测试

@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"));  
}

回答by Mehdi

These two utility methods could write to and read from Stringvia java.util.Propertiesobject:

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

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

I found the above two methods useful when there are plenty of properties and you want to save all of them in a storage or database, and you don't want to create a huge key-valuestore table.

我发现当有很多属性并且您想将所有属性保存在一个 中storage or database,并且您不想创建一个巨大的key-value商店表时,我发现上述两种方法很有用。