欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

解决Java中properties文件编码问题

程序员文章站 2021-11-23 10:46:01
目录1、properties文件显示乱码问题2、读取properties文件乱码3、spring boot的@configurationproperties读取properties文件乱码总结1、pr...

1、properties文件显示乱码问题

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

解决Java中properties文件编码问题

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来进行转换。
运行时显示如下图:

解决Java中properties文件编码问题

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

//加注解
@component
@configurationproperties(prefix = "yaml")
@propertysource(value = {"classpath:yaml.properties"}, encoding = "utf-8")
 

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

总结

到此这篇关于解决java中properties文件编码问题的文章就介绍到这了,更多相关java properties编码问题内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!

相关标签: Java properties