java Properties存储中文乱码

默认情况下Properties使用方法 store(OutputStream out, String comments) 将键值对存储到本地文件,若是有中文 会出现乱码,
若是直接将乱码读回到 java 里,是可以成功读回的,没有乱码问题

Properties properties = new Properties();
properties.setProperty("nj","najing");
properties.setProperty("bj","北京");

properties.store(new FileOutputStream("./a.txt"),"xxxx哈哈哈");  //出现乱码
properties.load(new FileInputStream("./a.txt"));   //读取乱码文件,读回时 是正常的

//============================
properties.store(new FileWriter("./a.txt"),"xxxx哈哈哈");  //不出现乱码
properties.load(new FileReader("./a.txt"));   //不出现乱码  正常的

//================指定编码 utf8 ============
properties.store(new OutputStreamWriter(new FileOutputStream("./a.txt"), "utf8"),"xxxx哈哈哈");  //idea 默认编码 utf8 ,文件./a.txt打开编码正常
properties.load(new FileReader("./a.txt"));  //使用字符流 读回 正常
properties.load(new FileInputStream("./a.txt"));//使用字节流 读回 不正常  汉字乱码

//================指定编码 GBK ============
properties.store(new OutputStreamWriter(new FileOutputStream("./a.txt"), "GBK"),"xxxx哈哈哈");  //idea 默认编码 utf8 ,文件./a.txt打开编码不正常 乱码
properties.load(new FileReader("./a.txt"));  //使用字符流 不正常  汉字乱码
properties.load(new FileInputStream("./a.txt"));//使用字节流 读回 不正常  汉字乱码

//============== 转换流 可以指定编码 ==================
OutputStreamWriter utf8 = new OutputStreamWriter(new BufferedOutputStream(new FileOutputStream("")), "utf8");

OutputStreamWriter
 

public class OutputStreamWriter extends Writer

OutputStreamWriter是字符的桥梁流以字节流:向其写入的字符编码成使用指定的字节charset 。 它使用的字符集可以由名称指定,也可以被明确指定,或者可以接受平台的默认字符集

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值