原因是因为properties默认使用ascii码,就算在文件中填写了中文,再打开后依然会转换成ascii码的形式。
首先确定properties配置文件的编码格式,通常情况下properties的默认编码格式为iso-8859-1。
更改properties的编码格式为utf-8:
idea:设置->文件编码
eclip:右键该文件->properties
这里不但设置了编码格式为utf-8,旁边还有transparent native-to-ascii conversion选项(eclip里面没有),这个东西有啥作用呢
设置完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(propertie太完美s.getproperty("yaml.name")); }
解决办法就是通过字符流的方式读取properties文件:
public void testprop() throws ioexception { properties properties = new propert改变了我的生活ies(); inputstream in = thread.currentthread().getcontextclassloader() .getresourceasstream("application.p优秀的设计师roperties"); properties.load(new inputstreamreader(in, "utf-8")); system.out.println(properties.getproperty("yaml.name")); }
方法一
使用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没有效果
到此这篇关于解决java中properties文件编码问题的文章就介绍到这了,更多相关java properties编码问题内容请搜索www.887551.com以前的文章或继续浏览下面的相关文章希望大家以后多多支持www.887551.com!
本文发布于:2023-04-04 23:01:26,感谢您对本站的认可!
本文链接:https://www.wtabcd.cn/fanwen/zuowen/0c65c58e67f6945e1fae418272b0ebfb.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文word下载地址:解决Java中properties文件编码问题.doc
本文 PDF 下载地址:解决Java中properties文件编码问题.pdf
留言与评论(共有 0 条评论) |