您的位置:首页 > 编程语言 > Java开发

Java定义一个用来保存全局字符串的properties文件并用ResourceBundle读取它

2016-06-13 15:16 555 查看
项目中的字符串应该统一管理

Properties类可以读取.properties文件,但太麻烦了。

因为项目中的字符串都在.properties文件里,每个类,注意:是每一个类都需要添加8行代码而且使用很不方便,代码如下:

InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("ipConfig.properties");
Properties p = new Properties();
try {
p.load(inputStream);
} catch (IOException e1) {
e1.printStackTrace();
}
String name = p.getProperty("name");
String description = p.getProperty("description");


Stop!

ResourceBundle才是我们需要的!

//hello.properties文件在包com.your_app下
private static final ResourceBundle RESOURCE_BUNDLE = ResourceBundle.getBundle("com.your_app.hello");
//如果properties文件位置为src/hello.properties
//private static final ResourceBundle RESOURCE_BUNDLE = ResourceBundle.getBundle("hello");
String name = RESOURCE_BUNDLE.getString(name);
String description = RESOURCE_BUNDLE.getString(description );


不过,ResourceBundle读取properties文件统一使用iso8859-1编码,无论系统的默认编码是什么。所以在.properties里面,不能直接使用中文之类文字,而是要通过native2ascii转乘\uxxxx这种形式

假设电脑设置的地区是中国大陆,语言是中文

那么你向ResourceBundle(资源约束名称为base)获取abc变量的值的时候,ResourceBundle会先后搜索

base_zh_CN_abc.properties

base_zh_CN.properties

base_zh.properties

base.properties

文件,直到找到abc为止
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息