Thursday, September 3, 2015

Java: "unmappable character for encoding ASCII"

I hit a strange compile error today: a project that compiled in several environments was failing to build in a build server. The error was in the "copyright" symbol in all .java files, something like...

...../.../MyFile.java:8: error: unmappable character for encoding ASCII
 *  ?? Copyright XX All Rights Reserved

     ^

Note that "file MyFile.java" showed UTF8, and this was indeed its encoding. Turns out Java was deciding or guessing it was ASCII, incorrectly.

One solution was to force the encoding, like this:
export JAVA_TOOL_OPTIONS=-Dfile.encoding=UTF8  
And even better, since I use Gradle, was to use compileJava.options.encoding. In my top-level gradle file:
subprojects {
    apply plugin: 'java'    compileJava.options.encoding = 'UTF-8'
... 

I hope this helps someone else!