Java基础练习题 (9)资源文件

来源:互联网 发布:网络作家猫腻 金泰妍 编辑:程序博客网 时间:2024/06/05 02:12

(1)如何用 Properties 类读取 .properties 文件?
Properties 类是 Hashtable 的子类,常用的方法有:

  • load(InputStream inStream),load(Reader reader) 【读取文件】
  • getProperty(String key) 【获取属性值】
  • setProperty(String key, String value) 【设置属性值】
  • store(OutputStream out, String comments),store(Writer writer, String comments) 【将该对象的属性列表存储到输出流中】
public static void main(String[] args) {  Properties properties = new Properties();  String filePath = "";//文件路径  try {    properties.load(new FileInputStream(filePath));//读取文件  } catch (FileNotFoundException e) {    e.printStackTrace();  } catch (IOException e) {    e.printStackTrace();  }}

(2)如何用 ResourceBundle 类读取 .properties 文件?
通常使用下面 ResourceBundle 类的两个静态方法

  • getBundle(String baseName)
  • getBundle(String baseName, Locale locale)

baseName 是文件路径,应包括完整包名,比如说在 demo 包里面有一个配置文件 resource_en.properties,那么 baseName 就应该是 “demo.resource”,不需要 properties 后缀。如果不传入 Locale,就会使用默认的地区信息。

(3)如何用 ResourceBundle 实现程序界面的多语言支持?
通过不同的地区获取不同的配置文件内容,就能实现多语言支持。比如我们有两个资源文件,

  • resource_zh.properties
  • resource_en.properties

里面有不同的语言信息,在读取时指定地区, ResourceBundle 就会读取相应的文件

ResourceBundle bundle = ResourceBundle.getBundle("demo.resource", Locale.CHINA); //读取 resource_zh.properties 文件bundle.getString(key); //读取该 key 对应的值
原创粉丝点击