自己写 JAVA 程序处理含有中文的属性文件(不使用native2ascii )

来源:互联网 发布:淘宝回复好评模板 编辑:程序博客网 时间:2024/05/16 06:48

对于普通的属性文件来说, 如果不含有中文,则使用 java.util.Properties 就很简单。但是如果含有中文,就会出现乱码,这是因为 Properties  是基于 unicode 来处理的。这时,我们就需要使用 jdk 自带的 native2ascii 工具进行转换:

C:/>native2ascii userInfo.properties userInfoUni.properties

 

但是在我们的应用程序中,对于需要经常配置的文件来说,用户可能并不想这样麻烦。因此我们考虑自己写程序来读取属性文件。程序非常简单,用 InputStreamReader 和 BufferedReader 就可以操作。我们将类编写成类似于 java.util.Properties 的操作方式。

 

package com.zxn.properties;

 

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Properties;
import java.util.Set;

 

public class PropertiesUnicode
{
    Properties props = null;

    public PropertiesUnicode()
    {
       props = new Properties();
    }
 
   public Properties load( InputStream inStream ) throws IOException
   {
      try
      {
         InputStreamReader  isr = new InputStreamReader(inStream);
         BufferedReader fr = new BufferedReader( isr );
         String s;
         while ( (s = fr.readLine()) != null )
         {
            int index = s.indexOf( "=" );
            if ( index > 0 )
            {
               String key = s.substring( 0, index );
               String value = s.substring( index+1 );
               props.put( key.trim(), value.trim() );
            }
         }
      }
      catch (IOException e)
      {
         // TODO Auto-generated catch block
         //e.printStackTrace();
         throw e;
      }
  
     return props;
 }
 
 public String getProperty( String key )
 {
    return props.getProperty( key );
 }
 
 public Set<Object> keySet()
 {
    return props.keySet();
 }

}

 

 

原创粉丝点击