Java Multiline Properties

A channel member asked if there was a way to do multiline properties in Java, and if so, how was leading whitespace handled?

The answers are, respectively, “yes,” and “pretty much as you’d hope it was.”

The multiline character for Java properties is, as one might expect from every other programming language’s usage, the \ character, and the Properties.load() method will trim all leading whitespace from the property value. Here’s a sample:

// This is Example.java
package example;

class Example {
  public static void main(String[] args) {
// sorry for the gross formatting here, page width! try(var in=Example
.class
.getResourceAsStream("/foo.properties")) { var properties=new Properties(); properties.load(in); System.out.println(properties.getProperty("foo")); } } }

And the properties file, foo.properties, which should be visible in the classpath at the root:

# this is /foo.properties
# note how "multiline" is indented more than the rest
foo = this \
  is \
  a \
    multiline \
  property

If this is run and the classpath is set properly, the output should be this is a multiline property. You can embed newlines with \n as desired as well, if you need those in the output.

Leave a Reply