spring boot commandline runner is using windows de

2019-05-26 17:54发布

I am running spring boot application on windows and its using windows-1252 encoding. However stand alone java program is using UTF-8 encodeing. How do I force spring boot to use UTF-8. below code outputs ????. I use the below command using jar -jar target\spring-boot-example.jar

I verified that in power shell program that default character set is windows-1252 (System.Text.Encoding)::Default

public class SpringBootConsoleApplication implements CommandLineRunner {
public static void main(String[] args) throws Exception {
    SpringApplication.run(SpringBootConsoleApplication.class, args);
}

    @Override
    public void run(String... args) throws Exception {
        System.out.println("Default Charset=" +   Charset.defaultCharset());
        System.out.println("test::" +"الرياض");        
    }
}

I tried the below options in application.properties without success:

# Charset of HTTP requests and responses. Added to the "Content-Type"    header if not set explicitly.
 spring.http.encoding.charset=UTF-8
 # Enable http encoding support.
 spring.http.encoding.enabled=true
 # Force the encoding to the configured charset on HTTP requests and   responses.
 spring.http.encoding.force=true

3条回答
Luminary・发光体
2楼-- · 2019-05-26 18:02

The problem seems to be your stdout, not the code. I suggest you create a simple main class, without Spring Boot, or any external dependencies, and print UTF-8 characters. I'm on a Mac, and the following code prints find for me:

public class Main {

    public static void main(String[] args) {
        System.out.println("Default Charset=" + Charset.defaultCharset());
        System.out.println("test::" + "الرياض");
    }
}

Default Charset=UTF-8
test::الرياض

Another thing you may want to try is writing it to a file instead of stdout.

Edit:

I think you're barking the wrong tree. No one uses Spring Boot for printing to stdout. The spring.http.encoding properties you'd set are actually HttpEncodingProperties which Boot uses to auto configure encoding using HttpEncodingAutoConfiguration. But all that's for a HTTP request, not for printing to stdout. Any application that deserves to go to Prod should use a logger, and not System.out.println.

查看更多
啃猪蹄的小仙女
3楼-- · 2019-05-26 18:25

Try running your app with -Dfile.encoding=UTF8 in the command line.

Example:

java -jar -Dfile.encoding=UTF8 target/myapp-0.0.1-SNAPSHOT.jar

查看更多
The star\"
4楼-- · 2019-05-26 18:25

@AbjitSarkar @JC Carrillo this issue seems to be with windows environment. I deployed the same code on UbuntuVM and everything seems to be fine.

Thank you for listening to me and giving me tips to explore !!

查看更多
登录 后发表回答