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 w
These two utility methods could write to and read from String via java.util.Properties object:
/**
* 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 hugekey-valuestore table.