一般使用到properties配置文件,一般都是在spring项目里面,直接由框架帮你读,当然,你也得考虑到编码的问题。但是现在要是要求使用Java直接读写properties文件,就发现很多的问题,比如,我的properties文件的编码
一般使用到properties配置文件,一般都是在spring项目里面,直接由框架帮你读,当然,你也得考虑到编码的问题。
但是现在要是要求使用Java直接读写properties文件,就发现很多的问题,比如,我的properties文件的编码竟然不是utf-8的。或者说我压根就没考虑到这个问题。
再比如,当properties文件里面有汉子的时候,发现读写的汉字乱码了,在我这是因为我的电脑默认编码是gbk,但是读的时候,又没有设置编码,搞出的问题。
下面直接上代码,看问题。
package com.lxk.propertyFileTest; import java.io.*; import java.util.Properties; public class Main { public static void main(String[] args) { Properties prop = new Properties(); InputStream in = null; FileOutputStream oFile = null; try { in = new BufferedInputStream(new FileInputStream("D:config.properties")); //prop.load(in);//直接这么写,如果properties文件中有汉子,则汉字会乱码。因为未设置编码格式。 prop.load(new InputStreamReader(in, "utf-8")); for (String key : prop.stringPropertyNames()) { System.out.println(key + ":" + prop.getProperty(key)); } //保存属性到b.properties文件 oFile = new FileOutputStream("b.properties", false);//true表示追加打开,false每次都是清空再重写 prop.setProperty("phone", "10086"); //prop.store(oFile, "此参数是保存生成properties文件中第一行的注释说明文字");//这个会两个地方乱码 //prop.store(new OutputStreamWriter(oFile, "utf-8"), "汉字乱码");//这个就是生成的properties文件中第一行的注释文字乱码 prop.store(new OutputStreamWriter(oFile, "utf-8"), "lll"); } catch (Exception e) { System.out.println(e.getMessage()); } finally { if (in != null) { try { in.close(); } catch (IOException e) { System.out.println(e.getMessage()); } } if (oFile != null) { try { oFile.close(); } catch (IOException e) { System.out.println(e.getMessage()); } } } } }
--结束END--
本文标题: Java读写.properties文件解决中文乱码问题
本文链接: https://www.lsjlt.com/news/221242.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
下载Word文档到电脑,方便收藏和打印~
2024-05-03
2024-05-03
2024-05-03
2024-05-03
2024-05-03
2024-05-03
2024-05-03
2024-05-03
2024-05-03
2024-05-03
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0