Published:

Fixing Java file encoding problems in Gradle

If you have Java file encoding problems when building with Gradle, make sure to explicitly set the file encoding option of the Java compiler.

...
apply plugin: 'java'
compileJava.options.encoding = 'UTF-8'
...

Explanation

When not setting the compiler encoding option explicitly, the problem you can run into is, that the Java compiler uses a different file encoding (in Gradle's case the system's default encoding) than the source code files are encoding in.

It happened to me that I had my Java code files encoded in UTF-8, Intellij IDEA compiling with UTF-8 during development (simply because it's faster), but Gradle compiling with the platform default encoding (e.g. Cp1252).

In my case I had a German umlaut in a string literal that ended up as an unknown character in the compiled class.

Published by Robert Möstl

« Back to Blog