Since Java 9 the default for .properties of PropertyResourceBundles is UTF-8 as stated here so you might have a good reasons to write properties with the UTF-8 symbols.
For the org.apache.commons.configuration2, you can achieve this by overriding the default ValueTransformer used for escaping characters
Kotlin code:
import org.apache.commons.configuration2.PropertiesConfiguration import org.apache.commons.configuration2.PropertiesConfiguration.DefaultIOFactory import org.apache.commons.configuration2.PropertiesConfiguration.PropertiesWriter import org.apache.commons.configuration2.convert.ListDelimiterHandler import org.apache.commons.configuration2.convert.ValueTransformer import org.apache.commons.text.translate.AggregateTranslator import org.apache.commons.text.translate.EntityArrays import org.apache.commons.text.translate.LookupTranslator import java.io.ByteArrayInputStream import java.io.InputStream import java.io.StringWriter import java.io.Writer /** * This class is custom implementation of the [ValueTransformer] that prevents escaping of UTF-8 characters * UTF-8 is supported in properties files by Java 9 */ private class Utf8ValueTransformer : ValueTransformer { companion object { private val charsEscape = mapOf<CharSequence, CharSequence>("\\" to "\\\\") private val escapeProperties = AggregateTranslator( LookupTranslator(charsEscape), LookupTranslator( EntityArrays.JAVA_CTRL_CHARS_ESCAPE ) ) } override fun transformValue(p0: Any?): Any { val strVal = p0.toString() return escapeProperties.translate(strVal) } }
Then you have to extend the DefaultIOFactory:
private class Utf8IoFactory : DefaultIOFactory() { companion object { private val valueTransformer = Utf8ValueTransformer() } override fun createPropertiesWriter(out: Writer?, handler: ListDelimiterHandler?): PropertiesWriter { return PropertiesWriter(out, handler, valueTransformer) } }
And finally you can get the result with UTF-8 characters:
private fun PropertiesConfiguration.asByteArray(): ByteArray { val writer = StringWriter() this.ioFactory = Utf8IoFactory() this.write(writer) return writer.toString().toByteArray() }