When compiling, running tests, or running a main class, gradle launches java with an explicit file.encoding, for example:
/usr/bin/java -Dfile.encoding=ISO-8859-1 -Duser.country=GB -Duser.language=en
-Duser.variant -cp … com.foo.MyMainClass
How does gradle select this default file encoding (which is ISO-8859-1 for me)? To switch to UTF-8, I have to add the following to my gradle build script:
allprojects {
tasks.withType(JavaCompile) {
options.encoding = 'UTF-8'
}
tasks.withType(Test) {
systemProperty 'file.encoding', 'UTF-8'
}
tasks.withType(JavaExec) {
systemProperty 'file.encoding', 'UTF-8'
}
}
which sets -Dfile.encoding=UTF-8.
Update #1
rzwitserloot noted that gradle is likely using the default encoding, which appears to be true.
PrintCharset.java
import java.nio.charset.Charset;
public class PrintCharset {
public static void main(String[] args) {
System.out.println("Default: " + Charset.defaultCharset());
}
}
Then, javac PrintCharset.java && java PrintCharset prints
Default: ISO-8859-1
Interestingly, running from IntelliJ (without gradle) executes:
/usr/bin/java -javaagent:… -Dfile.encoding=UTF-8 -classpath … PrintCharset
which, of course, prints Default: UTF-8.
Update #2
Digging a little deeper out of curiosity, the default charset in OpenJDK on linux is ultimately determined by nl_langinfo():
printlang.c
#include <langinfo.h>
#include <locale.h>
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
setlocale(LC_ALL, "");
printf("%s\n", nl_langinfo(CODESET));
exit(EXIT_SUCCESS);
}
Then, gcc -o printlang printlang.c && ./printlang prints ISO-8859-1.