Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Properties object to String

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 called 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?

like image 332
Casey Crites Avatar asked Oct 16 '09 16:10

Casey Crites


People also ask

What does ${ mean in a properties file?

The properties files are processed in the order in which they appear on the command line. Each properties file can refer to properties that have already been defined by a previously processed properties file, using ${varname} syntax.

How do you read the properties of an object in Java?

Properties is a subclass of Hashtable. It is used to maintain a list of values in which the key is a string and the value is also a string i.e; it can be used to store and retrieve string type data from the properties file. Properties class can specify other properties list as it's the default.

Is Java Util properties thread safe?

This class is thread-safe: multiple threads can share a single Properties object without the need for external synchronization.


1 Answers

public static String getPropertyAsString(Properties prop) {    
  StringWriter writer = new StringWriter();
  prop.list(new PrintWriter(writer));
  return writer.getBuffer().toString();
}
like image 83
lsiu Avatar answered Oct 13 '22 10:10

lsiu