Home > Software engineering >  How can I set Dfile.encoding=utf-8 when building maven project?
How can I set Dfile.encoding=utf-8 when building maven project?

Time:01-05

System.out.println(Charset.defaultCharset().displayName()); prints ISO-8859-1, so I want to set the defaultCharset to UTF-8.

When tried with java -Dfile.encoding=utf-8 -jar XXX.jar, I checked that default charset is set to UTF-8.

But is there a way to set Dfile.encoding=utf-8 option at maven packaging level, so that I can just run java -jar XXX.jar?

What I tried:

  • mvn clean package -Dfile.encoding=utf-8

  • pom.xml

            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-surefire-plugin</artifactId>
                <version>2.19.1</version>
                <configuration>
                    <argLine>-Dfile.encoding=utf-8</argLine>
                </configuration>
            </plugin>
  • MAVEN_OPTS="-Dfile.encoding=utf-8" mvn clean package

I prefer controlling with pom.xml file.

CodePudding user response:

You can define JDK_JAVA_OPTIONS environment variable as -Dfile.encoding=utf-8 to avoid typing it every time. See the java command documentation for details.

In OpenJDK 18 UTF-8 will be default for all operating systems: JEP 400.

CodePudding user response:

You are using the maven surefire plugin in the example. I assume you have to run some tests since you use it. And your tests require specific file encoding.

It's possible to configure the surefire plugin in this way:

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-surefire-plugin</artifactId>
    <version>2.19.1</version>
    <configuration>
        <systemProperties>
            <property>
                <name>file.encoding</name>
                <value>utf-8</value>
            </property>
        </systemProperties>
    </configuration>  
</plugin>

Note that the example provided for version 2.19.1, it's Deprecated in the latest version:

https://maven.apache.org/surefire/maven-surefire-plugin/examples/system-properties.html

Update:

The question is how to pass JVM args for Maven build before runtime.

Starting with Maven 3.3.1 you can define JVM configuration via ${maven.projectBasedir}/.mvn/jvm.config file which means you can define the options for your build on a per project base. This file will become part of your project and will be checked in along with your project.

So, create .mvn/jvm.config in your project root with content:

-Dfile.encoding=utf-8

See the reference: https://maven.apache.org/configure.html#mvn-jvm-config-file

  •  Tags:  
  • Related