ResourceBundle 使用

Java ResourceBundle 理解

1. 基础
  • java.util 包下的工具类

  • ResourceBundle 是用来处理properties文件的类

  • ResourceBundle 是用来做国际化的,配合多个properties文件

2. 配置

1539182191512

  • 建立properties文件 (自定义名字_地区字符.properties文件)

    • 比如:

      mySource_en_US.properties
      mySource_zh_CN.properties

      mySource.properties (默认)

      mySource_en_US.properties
      title=welcome
      
      mySource_zh_CN.properties
      title=欢迎
      
      mySource_en_US.properties
      title=欢迎你
      
3. 使用

public class TestResourceBundle {
    public static void main(String[] args) {
        //设置地区美国
        Locale.setDefault(Locale.US);
        System.out.println("US " + TestResourceBundle.getValue());
        //设置地区中国
        Locale.setDefault(Locale.SIMPLIFIED_CHINESE);
        System.out.println("CN " + TestResourceBundle.getValue());
        //没有配置的地区
        Locale.setDefault(Locale.GERMAN);
        System.out.println("Other " + TestResourceBundle.getValue());
    }

    private static String getValue() {
        ResourceBundle resourceBundle = ResourceBundle.getBundle("sourceBundle.mySource");
        String value = resourceBundle.getString("title");
        value = new String(value.getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8);
        return value;
    }
}

输出结果:

US welcome
CN 欢迎
Other 欢迎你

你可能感兴趣的:(java,util)