Source file encoding is another example of a tiny problem that needs a surprisingly big amount of Gradle code. There is a pretty old issue for this, so if you think that the code below is too complicated (like I do), please vote for it.

Java files

Gradle uses the platform encoding as default encoding for Java files (like the Java compiler does), which is a bad choice for platform-independent applications. To change this, add the following snipplet to your build.gradle file:

apply plugin: "java"
tasks.withType(JavaCompile) {
  options.encoding = "UTF-8"
}

This is because we have at least two instances of a JavaCompile task (“compileJava” and “compileTestJava”), and the encoding must be applied to all of them. Note that early versions of Gradle use type Compile instead.

Groovy files

GroovyCompile tasks have different encoding settings for Java and Groovy files:

apply plugin: "groovy"
tasks.withType(GroovyCompile) {
  options.encoding = "UTF-8" // for Java compilation
  groovyOptions.encoding = "UTF-8" // for Groovy compilation
}

In the current case, the groovyOptions.encoding line is optional, since UTF-8 is the default encoding for Groovy files.

Eclipse integration

The Eclipse Plugin ignores the encoding settings, so we must create the corresponding configuration file manually, as documented in the issue mentioned above:

apply plugin: "eclipse"
eclipseJdt << {
  file(".settings/org.eclipse.core.resources.prefs").text
      = "eclipse.preferences.version=1\nencoding/<project>=UTF-8"
}

Intellij IDEA integration

Again, no out-of-the-box encoding support with the IDEA plugin. We must add a new XML node to the XML project file:

apply plugin: "idea"
idea {
  project {
    ipr {
      withXml { xmlProvider ->
        def encoding = xmlProvider.asNode().component.find { it.@name == "Encoding" }
        encoding.appendNode("file", [url: "PROJECT", charset: "UTF-8"])
      }
    }
  }
}

The sample code is based on this Gradle goodness posting and tested with IDEA 14.

comments powered by Disqus