java Properties 读取文件,国际化

Properties类可以看成一个持久化的Properties文件
Properties文件可以被保存到一个流中或者从流载入
每一个键及其对应值在Properties中都必须是String类型.
注意:Properties文件必须在工程项目下面

import java.io.*;
import java.util.*;
public class PropertiesTest {
    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Properties pro=new Properties ();
        try{
            pro.load(new FileInputStream("config.txt"));            
        }catch(Exception e){
            e.printStackTrace();
        }        
        Enumeration<String> e=(Enumeration<String>) pro.propertyNames();
        while(e.hasMoreElements()){
            String key=e.nextElement();
            System.out.println(key+":"+pro.getProperty(key));
        }
    }
}

资源文件config.txt内容:

name=jhtchina
Age=35
sex=man

实现对配置文件变量的遍历。国际化问题

import java.util.*;
public class hello {
    private static void testResourceBundle(ResourceBundle resource) {
        // 取得所有内容
        Enumeration<String> enu = resource.getKeys();

        while (enu.hasMoreElements()) {
        String key = enu.nextElement();
        System.out.println(key + ": " + resource.getString(key));
        }
        System.out.println();
        }
    
    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        /*
        ResourceBundle res=ResourceBundle.getBundle("Message");
        System.out.println(res.getString("name"));
        */
        Locale myLocale =Locale.getDefault();// Locale.getDefault();//获得系统默认的国家/语言环境        
        ResourceBundle bundle = ResourceBundle.getBundle("baseName",myLocale);
        //System.out.println(bundle.getString("who"));
        testResourceBundle(bundle);    
    }
}

资源文件

baseName_en_US.properties

hello=Hello

baseName_zh_CN.properties

#chinese
#hello=吃饭了吗?
#who=请问,你是谁?
#native2ascii -encoding UTF-8   resources-filename    destination-filename
hello=\u5403\u8FC7\u996D\u4E86\u5417\uFF1F
who=\u8BF7\u95EE\uFF0C\u4F60\u662F\u8C01\uFF1F

注意汉字需要采用native2ascii.exe进行转换方可。文件名的命名是前缀+后面图给的标准。资源文件和程序文件在同一个目录下面。
(1)Locales语言环境
一个Locale对象表示一个特定的地理、政治或文化的地区。
在JDK中预定义的国家对象:
Locale.CANADA
 Locale.CANADA_FRENCH
Locale.CHINA
Locale.FRANCE
Locale.GERMANY
Locale.ITALY
Locale.JAPAN
Locale.KOREA
Locale.PRC
Locale.TAIWAN  //but we know TAIWAN is not a country!
Locale.UK
Locale.US
在JDK中预定义的语言对象:
Locale.CHINESE
Locale.ENGLISH
Locale.FRENCH
Locale.GERMAN
Locale.ITALIAN
Locale.JAPANESE
Locale.KOREAN
Locale.SIMPLIFIED_CHINESE
Locale.TRADITIONAL_CHINESE

构造函数:
Locale german = new Locale("de");
Locale germanGermany = new Locale("de", "DE");
Locale germanSwitzerland = new Locale("de", "CH");
Locale norwegianNorwayBokmal = new Locale("no", "NO", "B");

常用的语言和国家代码,注意资源原件对应的命名规则

(2) 资源包
Java的ResourceBundle类可以解决这种形式的文档,并且将资源文件的内容解析为键-值对形式
以“#”开头的行作为一个注释行,ResourceBundle类将忽略该行不给于处理;
资源文件的文件名命名规则:basename_语言代码_国家代码.properties

posted @ 2014-07-25 15:05  jhtchina  阅读(770)  评论(0)    收藏  举报