18

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?

9 Answers 9

32
public static String getPropertyAsString(Properties prop) {    
  StringWriter writer = new StringWriter();
  prop.list(new PrintWriter(writer));
  return writer.getBuffer().toString();
}
Sign up to request clarification or add additional context in comments.

2 Comments

It's worth noting that this will not give you a straight rendering of the properties back, i.e. you can't just pop out that string into a file and load it back as a properties file. This is because that Properties.list() method prepends a header onto the list: -- listing properties -- More likely you'd want to use the Properties.store() method described in the comment from @joev comment below.
bad and ugly recomendation because this have unexcepted beahviour: (var5.length() > 40) and
18

There seems to be a problem with @Isiu answer. After that code Properties are truncated, like there is some limit to string length. Proper way is to use code like this:

public static String getPropertyAsString(Properties prop) { 
    StringWriter writer = new StringWriter();
    try {
        prop.store(writer, "");
    } catch (IOException e) {
        ...
    }
    return writer.getBuffer().toString();
}

1 Comment

You get a header with a time stamp with that method.
9

It's not directly related to your question but if you just want to print out properties for debugging you can do something like this

properties.list(System.out);

1 Comment

Or even just call .toString() if you're using a logging solution. It uses ConcurrentHashMaps implementation.
6

If you are using Java 8 or above, here is a single statement solution with the possibility to control the format by yourself:

String properties = System.getProperties().entrySet()
            .stream()
            .map(e -> e.getKey() + ":" + e.getValue())
            .collect(Collectors.joining(", "));

Comments

2

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.

Comments

1

You can do as below also:

Properties p = System.getProperties();
Enumeration keys = p.keys();
while (keys.hasMoreElements()) {
    String key = (String)keys.nextElement();
    String value = (String)p.get(key);
    System.out.println(key + ": " + value);
}

Comments

0

Another function to print all the values of a field is :

public static <T>void   printFieldValue(T obj)
{
    System.out.printf("###" + obj.getClass().getName() + "###");
    for (java.lang.reflect.Field field : obj.getClass().getDeclaredFields()) {
        field.setAccessible(true);
        String name = field.getName();
        Object value = null;
        try{
            value = field.get(obj);
        }catch(Throwable e){}
        System.out.printf("#Field name: %s\t=> %s%n", name, value);
    }
}

Comments

0

Using the list method is incorrect because it should be used only for debugging purposes

Prints this property list out to the specified output stream. This method is useful for debugging.

It doesn't escape keys which contains special characters, like = or :.

The store method should be used, but it inserts a comment and timestamp. The following code removes these additional lines and returns a text with normalized new lines.

Java

public static String propertiesToString(Properties properties) throws IOException {
    if (properties == null) {
        return null;
    }
    if (properties.isEmpty()) {
        return "";
    }
    StringWriter writer = new StringWriter();
    properties.store(writer, null);
    String text = normalizeNewLines(writer.toString());
    List<String> lines = new ArrayList<>(Arrays.asList(text.split("\n")));
    lines.remove(0);
    return lines.stream().collect(Collectors.joining("\n"));
}

private static String normalizeNewLines(String text) {
    return text.replace("\r\n", "\n").replace("\r", "\n");
}

Groovy

static String propertiesToString(Properties properties) {
    if (properties.is(null)) {
        return null
    }
    if (properties.isEmpty()) {
        return ''
    }
    def writer = new StringWriter()
    properties.store(writer, null)
    def lines = normalizeNewLines(writer).split('\n') as List
    lines.remove(0)
    return lines.join('\n')
}

private static String normalizeNewLines(String text) {
    return text.replace('\r\n', '\n').replace('\r', '\n')
}

Comments

0
Properties properties;
new HashMap<>(properties).toString()
    .replace(',', '\r');

without values truncation. The replace call is for the case if you want to list properties in a column.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.