Java: possible to line break in a properties file?
To insert a line break in a Java properties file, simply place a backslash (\
) at the end of the line—ensure there are no trailing spaces.
Example:
Using line breaks in your properties files can greatly enhance readability and maintainability. It allows you to format even longer text entries without sacrificing the clarity of your code.
Line breaking long strings
Long strings in properties files can sometimes stretch your code beyond the comfortable limits. Here's how line breaks can come to rescue:
- The backslash has to be the last character on the line. Even a single space can break this feature.
- The leading spaces on the next line are ignored. This avoids unintentional leading whitespace in your property value.
- When using
getProperty()
, expect the value to come as a single, concatenated string. The line breaks only live in the properties file, not in your Java code.
Example:
Avoiding line break pitfalls
While implementing line breaks in your properties file, here are some things to watch out for:
- Invisible characters: Be sure that no space or any other invisible character sneaks in after the backslash.
- Property retrieval: The multiline properties will still appear as a single line when you retrieve them in your Java code.
- Comments: A line ending with a backslash followed by a comment line will cause an error. The parser tries to treat the comment as a continuation of the property, which is not correct!
Profiting from official documentation
Extracting insights from the Java documentation, keep in mind these:
- A logical line can span several physical lines. But Java perceives it as a single line.
- Whitespace, that comes after a line-continuing backslash, is not a part of the property value.
- Properties files support Unicode characters, meaning you can even use multiple languages inside a single property using
\uXXXX
notation.
Including these in your practice, you can handle multi-line and multi-language properties with great ease.
Was this article helpful?