java.util.ResourceBundle读取properties文件
2017-05-11 16:25
399 查看
ResourceBundle类的作用
基本作用就是读取资源中的properties文件实际应用:国际化
该类能够使你的程序- be easily localized, or translated, into different languages
- handle multiple locales at once
- be easily modified later to support even more locales
实例
国际化中Properties文件的命名格式为:自定义名字语言国家.properties比如英语和中文的写法分别是:errormsg_en_US.properties、errormsg_zh_CN.properties
并在两个文件中添加相应的内容
error.register.phoneDoesNotExist=The phone number does not exist
error.register.phoneDoesNotExist=电话号码不存在
Java代码如下:
import java.util.Locale; import java.util.ResourceBundle; public class TestResourceBundle { public static void main(String[] args) { printMessage(Locale.getDefault());//根据当前系统而定, printMessage(new Locale("zh", "CN")); printMessage(new Locale("en", "US")); } public static void printMessage(Locale locale) { ResourceBundle resourceBundle = ResourceBundle.getBundle("errormsg", locale); System.out.println(resourceBundle.getString("error.register.phoneDoesNotExist")); } }
控制台输出:
电话号码不存在(我的是中文系统,所以肯定输出了中文)
电话号码不存在
Sorry, the phone number does not exist
典型问题:Save could not be complete, some characters cannot be mapped using ISO-8859-1
普通的Properties的编码格式是ISO-8859-1,所以保存西方语系的字母时不会报错,当你输入中文或日文等文字时就保存不了了。两种解决方法
1. 直接点Save as UTF-8(不推荐)
但是问题来了,当你调用resourceBundle.getString("xxx")打印出来时变成乱码。有个解决方法,利用String类做编码转换
new String(resourceBundle.getString("xxx").getBytes("ISO-8859-1"), "UTF-8");
该方法有点笨,非常不方便,只要你用到中文的地方都要用一次New String作转换,对于程序员来说简直就是噩梦,于是聪明的开发者开发出了一种插件。
2. 下载Eclipse插件:propertiesEditor:(推荐)
该插件的作用是把中文自动转换为unicode格式。把下载到的插件中的plugins和futures分别添加Eclipse的plugins和futures文件夹中,重启Eclipse。你会发现
porperties文件的图标改变了。
说明插件安装成功。然后我们就可以Open with PropetiesEditor,愉快编辑和保存, 不会出现Save could not be complete这个问题了。
(PS: 虽然把中文自动转换为unicode格式,但是在编辑时中文还是显示为中文,不会是unicode。这一点很給力)
相关文章推荐
- java.util.ResourceBundle 和java.util.properties 读取配置文件区别
- 读取资源属性文件(properties)java.util.ResourceBundle使用详解
- Eclipse和Tomcat和Java读取配置文件工具类PropertiesUtil
- java读取配置文件(使用java.util.Properties读取)
- java使用java.util.Properties读取properties文件的九种方法
- 利用java.util.Properties读取属性文件
- java.util.ResourceBundle 和java.util.properties 读取配置文件区别
- Java的ResourceBundle读取properties文件
- 使用java.util.Properties读取配置文件信息
- Java定义一个用来保存全局字符串的properties文件并用ResourceBundle读取它
- 使用java.util.Properties读取文件
- java.util.Properties 读取资源文件
- java.util.Properties读取中文内容的配置文件,发生中文乱码的现象有解决方案
- 通过java.util.Properties类来读取.properties文件中key对应的value
- 属性文件读写java.util.Properties
- Java读取properties文件的六种方法
- Java Properties 类读取配置文件信息
- Java读取Properties文件的几种方法
- 读取/书写Java的XML格式properties文件
- Java Properties 类读取配置文件信息