1. 区别
- Properties 用来解析普通属性文件
- ResourceBundle 通常用于解析国际化资源属性文件, 会根据本地环境自动选择对应的国际化资源
2. 用法
1. Properties解析文件
-
先准备一个properties文件放在resource目录下:
name=小明 age=18
public class demo2 { public static void main(String[] args) { // ClassPathResource 是用于读取resource目录下文件,具体可以看下面的博客 // https://blog.csdn.net/xueyijin/article/details/121441738 try (InputStreamReader in = new InputStreamReader(new ClassPathResource("test.properties").getInputStream())) { Properties p = new Properties(); p.load(in); // Properties的遍历:https://blog.csdn.net/xueyijin/article/details/123968385 Set<Object> keySet = p.keySet(); for (Object key : keySet) { System.out.println(key + ":" + p.get(key)); } } catch (IOException e) { e.printStackTrace(); } } }
2. ResourceBundle
-
ResourceBundle 本身就是可以解析properties文件,因此也可以使用于解析properties文件
public class demo { public static void main(String[] args) { // 因为ResourceBundle 就是专门用于解析properties文件,因此不用加 .properties 后缀 ResourceBundle resourceBundle = ResourceBundle.getBundle("test"); Set<String> keys = resourceBundle.keySet(); for (String key : keys) { System.out.println(key +":" // 其实ResourceBundle解析文件,有点很麻烦的地方就是这个字符转化,比较繁琐 + new String(resourceBundle.getString(key).getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8)); } } }
-
但 ResourceBundle 核心的作用是 用于解析国际化资源属性文件, 会根据本地环境自动选择对应的国际化资源。
-
比如 在中国 name:小明,age:18,但在美国name=xiao_ming,age=eighteen,如下:
准备两个properties文件
test_en_us.propertiesname=xiao_ming age=eighteen
test_zh_cn.properties
name=小明 age=18
public class demo3 { public static void main(String[] args) { // ResourceBundle.getBundle("test", new Locale("en","us")) // 这里的意思:先在resource目录下找 test_en_us.properties文件 // 如果没有再找 test_en.properties文件 // 如果还是没有,则找test.properties文件,若还是没有,则报错了 // 想 new Locale的两个参数,就可以改成配置变量,即可切换对应的properties内容了。 ResourceBundle resourceBundle = ResourceBundle.getBundle("test", new Locale("en","us")); final Set<String> keys = resourceBundle.keySet(); for (String key : keys) { System.out.println(key +":" + new String(resourceBundle.getString(key).getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8)); } } }