Java properties编码问题

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

Java properties编码问题

KING丨殇痕   2022-05-23 我要评论

1、properties文件显示乱码问题

原因是因为properties默认使用ASCII码,就算在文件中填写了中文,再打开后依然会转换成ASCII码的形式。
首先确定properties配置文件的编码格式,通常情况下properties的默认编码格式为ISO-8859-1。
更改properties的编码格式为UTF-8:
IDEA:设置->文件编码

在这里插入图片描述

eclipse:右键该文件->properties

这里不但设置了编码格式为UTF-8,旁边还有Transparent native-to-ascii conversion选项(eclipse里面没有),这个东西有啥作用呢

2、读取properties文件乱码

设置完properties文件编码格式为UTF-8后,一般我们通过字节流读取properties文件的方式会乱码:

    public void TestProp1() throws IOException {
        Properties properties = new Properties();
        InputStream in = Thread.currentThread().getContextClassLoader()
                .getResourceAsStream("application.properties");
        properties.load(in);
        System.out.println(properties.getProperty("yaml.name"));
    }

解决办法就是通过字符流的方式读取properties文件:

    public void TestProp() throws IOException {
        Properties properties = new Properties();
        InputStream in = Thread.currentThread().getContextClassLoader()
                .getResourceAsStream("application.properties");
        properties.load(new InputStreamReader(in, "UTF-8"));
        System.out.println(properties.getProperty("yaml.name"));
    }

3、Spring boot的@ConfigurationProperties读取properties文件乱码

方法一
使用yml文件
方法二
设置Transparent native-to-ascii conversion也就是上述图片上属性文件的配置勾选自动转换成ASCII,但显示原生的内容。
在IDEA勾选这个选项的作用就是:显示为UTF-8格式,但是运行时转换成ASCII的形式,实际上使用的是native2ascii.exe来进行转换。
运行时显示如下图:

在这里插入图片描述

方法三
添加注解@PropertySource并声明encoding=“UTF-8”

//加注解
@Component
@ConfigurationProperties(prefix = "yaml")
@PropertySource(value = {"classpath:yaml.properties"}, encoding = "UTF-8")
 

注意:这种方法只能对自定义的properties文件有效,对于spring boot默认生成的application.properties没有效果

总结

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们