Search code examples
scalaunicodepropertiesunicode-escapes

Convert special Characters to Unicode Escape Characters Scala


Hello is it possible to convert special Characters like Ä, Ö, Ü, ... to Unicode Escape Characters?
Like Ä would be \u00C4
I need this to convert a File for Translation purposes. I have a key value pair of Translations on Server Side e.g.:

hometown = München  

and want to parse it to de.properties to use it in my Javascript App.
.properties is by definiton ISO/IEC 8859-1 encoded http://en.wikipedia.org/wiki/.properties
So i have to parse the Key/Value Pair to:

hometown = M\u00FCnchen  

Is it possible to get these Escape Characters with Scala/Java?
EDIT:
Get unicode value of a character doesnt work for me. E.G. for Character Ä i get \u017D but i need to get \u00C4
EDIT TO MY EDIT:
Ah ok the problem was that i tried it on the Scala REPL. When i try

println( "\\u" + Integer.toHexString('Ä' | 0x10000).substring(1) )

it prints the correct escape character \u00C4


Solution

  • Rather than manually trying to do the escaping, use the tools the JVM gives you for working with .properties files. E.g. make an instance of the Properties you want, and then use Properties#store, which will handle the escaping for you.

    Response to edit: If you are getting out \u017D then you don't have an Ä - check your project source encoding and the encoding settings for anywhere you read data.