解决Java读取properties文件中文乱码的问题

问题的提出:初用properties,读取java properties文件的时候如果value是中文,会出现读取乱码的问题 
问题分析:开始以为是文件保存编码问题,把eclipse中所有的文件编码都修改成utf8,问题依然存在;把内容复制到notepad++进行utf8编码转换,问题依旧;上网搜索有人提议重写properties类或者用jdk自带的编码转换工具,嫌麻烦而且凭感觉jdk开发者不可能不考虑东亚几国的字符编码问题;因为properties文件操作的代码是参考百度文库里的一边文章的,分析其代码后,发现其用的是字节流来读取文件,具体代码如下: 
Java代码   收藏代码
  1. Properties properties = new Properties();  
  2. InputStream inputStream = this.getClass().getResourceAsStream("/menu.properties");  
  3. properties.load(inputStream );  
  4. System.out.println(properties.getProperty("a"));  

因为字节流是无法读取中文的,所以采取reader把inputStream转换成reader用字符流来读取中文。代码如下: 
Java代码   收藏代码
  1. Properties properties = new Properties();  
  2. InputStream inputStream = this.getClass().getResourceAsStream("/menu.properties");  
  3. BufferedReader bf = new BufferedReader(new    InputStreamReader(inputStream));  
  4. properties.load(bf);  
  5. System.out.println(properties.getProperty("a"));  


转换为string( ISO8859-1 -> utf-8

import  java.io.FileNotFoundException;   
import  java.io.IOException;   
import  java.util.Properties;   
        
public  class  CP {   
        
     private  static  final  String path =  "config/common.properties" ; //从src的根目录开始   
     private  static  final  String encode =  "UTF-8" ; //文件的编码格式   
     private  static  Properties props =  new  Properties();   
     static  {   
         try  {   
             props.load(Thread.currentThread().getContextClassLoader()   
                     .getResourceAsStream(path));   
         catch  (FileNotFoundException e) {   
             e.printStackTrace();   
         catch  (IOException e) {   
             e.printStackTrace();   
         }   
     }   
        
     public  static  String getValue(String key)  throws  Exception {   
         return  new  String(props.getProperty(key).getBytes( "ISO8859-1" ), encode);   
     }   
        
     public  static  void  updateProperties(String key, String value) {   
         props.setProperty(key, value);   
     }   
     public  static  void  main(String[] args)  throws  Exception{   
         System.out.println( "网站名称:" +CP.getValue( "site" ));   
     }   
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值