sunny123456

  博客园 :: 首页 :: 新随笔 :: 联系 :: 订阅 :: 管理 ::

java 读取properties java读取properties乱码,IDEA 更改显示格式


1. 打开properties文件,中文呈现乱码:

原因:文件格式问题,properties默认使用ISO8859-1格式,中文显示,通用的是utf-8, 带中文的可改成gbk, gb2312. 这里改成         utf-8即可。

步骤:打开 IDEA,进入 File -> Settings -> Editor -> File Encodings。 将 Global Encoding、Project Encoding 和 Default Encoding for Properties Files 均设为 UTF-8。 勾选 Transparent native-to-ascii conversion(自动将非 ASCII 字符转为 Unicode 转义序列)。

2.读取properties文件时出现乱码:eg: String username=property.getProperty(key);

原因:getProperty(key)是使用ISO8859-1来解码的,所以读取中文时会乱码,需要将读取出来的字符串从ISO8859-1再编码回         去,用文本的本身编码格式再解码。

解决方法:

       

在 String username=property.getProperty(key); 后增加:
         resultName=new String(username.getBytes("ISO-8859-1"),"gbk");
  • 1.
  • 2.

直接使用resultName就行。

3. (1)在Properties.load中:

    eg: java代码:

FileInputStream isr = new FileInputStream(savePath); 
         Properties props = new Properties(); 
         props.load(isr);
  • 1.
  • 2.
  • 3.

注意:isr 必须是文件字节流,不能是字符流,否则还是会乱码。(或者有解决办法,但是我还没找到!)

(2) 输出流:

eg: Java代码 

OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream(savePath), "UTF-8"); 
 props.store(osw,"This is the System Config file,Please don't delete or modify it!");
  • 1.
  • 2.
原文链接:https://blog.51cto.com/u_16099220/6336759
posted on 2024-07-08 15:17  sunny123456  阅读(604)  评论(0)    收藏  举报