views:

129

answers:

2

I have a Java Properties object that I load from an in-memory String, that was previously loaded into memory from the actual .properties file like this:

this.propertyFilesCache.put(file, FileUtils.fileToString(propFile));

The util (fileToString) actually reads in the text from the file and the rest of the code stores it in a HashMap (propertyFilesCache). Later, I read the file text from the HashMap as a String and reload it into a Java Properties object like so:

String propFileStr = this.propertyFilesCache.get(fileName);
Properties tempProps = new Properties();
try {
    tempProps.load(new ByteArrayInputStream(propFileStr.getBytes()));
} catch (Exception e) {
    log.debug(e.getMessage());
}
tempProps.setProperty(prop, propVal);

At this point, I've replaced my property in my in-memory property file and I want to get the text from the Properties object as if I was reading a File object like I did up above. Is there a simple way to do this or am I going to have to iterate over the properties and create the String manually?

A: 

I don't completely understand what you're trying to do, but you can use the Properties class' store(OutputStream out, String comments) method. From the javadoc:

public void store(OutputStream out, String comments) throws IOException

Writes this property list (key and element pairs) in this Properties table to the output stream in a format suitable for loading into a Properties table using the load(InputStream) method.

joev
+1  A: 
public static String getPropertyAsString(Properties prop) {    
  StringWriter writer = new StringWriter();
  prop.list(new PrintWriter(writer));
  return writer.getBuffer().toString();
}
lsiu
This did the trick, thanks!