java.util.Properties 的常见使用方法
By:Roy.LiuLast updated:2014-02-16
Properties 文件通常被用来当做 java 的配置文件使用,通过键值对来操作数据, 在实际的使用过程中,经常会有如下一些用法.
1. 从文件中得到 properties 的各种键值对。
2. 将Properties 对象保存到文件中.
3. 获取Properties 对象某个具体key的值, 如果没有给默认值的情况。
在项目中经常使用的几个处理Properties 的公用类
一个处理多语言自定义国际化的类, 也用来处理 porperties 文件
如果自己写一个多语言的应用程序,自己在应用程序总定义了如下几个国际化的文件:
1.application_zh_CN.properties
2.application_cn.properties
要的到文件里面国际化的内容也有通用的方法,当然,你可以采用上面的方法,一个更简单的方法如下:
这是常用来处理properties 文件的两个工具类,可以直接在项目中使用,也还有别的方法,与 properties 相关的操作方法,还可以参考这里:
Propeties文件与stream 之间的转换
1. 从文件中得到 properties 的各种键值对。
2. 将Properties 对象保存到文件中.
3. 获取Properties 对象某个具体key的值, 如果没有给默认值的情况。
在项目中经常使用的几个处理Properties 的公用类
package com.yihaomen.util;
/**
* 实现任意properties文件读写,支持各种字符集
*/
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Arrays;
public class PropertiesUtil extends ArrayList {
private static final long serialVersionUID = 6853092427667171450L;
// 设置字符集
private String encoding = "GBK";
private String fileName;
@SuppressWarnings("unchecked")
public PropertiesUtil(String fileName) {
try {
this.fileName = fileName;
if (!isFileExist(fileName))
this.write("");
this.addAll(Arrays.asList(read(fileName, encoding).split("\n")));
} catch (Exception ex) {
throw new RuntimeException("解析[" + fileName + "]出现异常!", ex);
}
}
@SuppressWarnings("unchecked")
public PropertiesUtil(String fileName, String encoding) {
try {
this.fileName = fileName;
this.setCharacterEncoding(encoding);
if (!isFileExist(fileName))
this.write("");
this.addAll(Arrays.asList(read(fileName, encoding).split("\n")));
} catch (Exception ex) {
throw new RuntimeException("解析[" + fileName + "]出现异常!", ex);
}
}
/**
* 设置字符集
*
* @param encoding
* @throws UnsupportedEncodingException
*/
@SuppressWarnings("unused")
private void setCharacterEncoding(String encoding)
throws UnsupportedEncodingException {
this.encoding = encoding;
}
private static boolean isFileExist(String fileName) {
return new File(fileName).isFile();
}
/**
* read file as single strings
*
* @return
* @throws IOException
*/
private static String read(String fileName, String encoding)
throws IOException {
StringBuffer sb = new StringBuffer();
BufferedReader in = new BufferedReader(new FileReader(fileName));
String s;
while ((s = in.readLine()) != null) {
sb.append(s);
sb.append("\n");
}
in.close();
return sb.toString();
}
/**
* write file as single strings
*
* @param text
* @throws IOException
*/
private void write(String text) throws IOException {
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(
fileName)));
out.print(text);
out.close();
}
/**
* save the content to file
*
* @throws IOException
*/
public void save() throws IOException {
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(
fileName)));
String tmp;
for (int i = 0; i < size(); i++) {
tmp = get(i) + "";
out.println(tmp);
}
out.close();
}
/**
* set properties file with a par key and value
*
* @param key
* @param val
* @throws UnsupportedEncodingException
*/
@SuppressWarnings("unchecked")
public void setProperties(String key, String val) {
int ipos = findKey(key);
if (ipos >= 0)
this.set(ipos, key + "=" + val);
else
this.add(key + "=" + val);
}
/**
* 查找KEY的序号
*
* @param key
* @return
*/
private int findKey(String key) {
try {
String tmp;
for (int i = 0; i < size(); i++) {
tmp = get(i) + "";
tmp = new String(tmp.getBytes("GBK"), encoding);
if (tmp.indexOf(key) == 0) {
return i;
}
}
} catch (Exception e) {
}
return -1;
}
/**
* 增加备注
*
* @param memo
*/
@SuppressWarnings("unchecked")
public void setMemo(String key, String memo) {
if ("".equals(key)) {
this.add("#" + memo);
return;
}
String tmp;
int ret = findKey(key);
if (ret == -1) {
this.add("#" + memo);
this.add(key + "=");
} else {
int ipos = ret - 1;
if (ipos < 0)
this.add(ipos, "#" + memo);
else {
tmp = this.get(ipos) + "";
if ("#".equals(tmp.substring(0, 1)))
this.set(ipos, "#" + memo);
else
this.add(ipos + 1, "#" + memo);
}
}
}
/**
* get the value of a key
*
* @param key
* @return
*/
public String getProperties(String key) {
return getProperties(key, "");
}
public String getProperties(String key, String defaultStr) {
if (key == null) {
return defaultStr;
}
String tmp, ret;
try {
for (int i = 0; i < size(); i++) {
tmp = get(i) + "";
tmp = new String(tmp.getBytes("GBK"), encoding);
if (tmp.indexOf(key) == 0) {
ret = tmp.substring(key.length() + 1);
return ret;
}
}
} catch (Exception ex) {
throw new RuntimeException("获取[" + fileName + "]中属性[" + key
+ "]的值出现异常!", ex);
}
return defaultStr;
}
// Simple test:
public static void main(String[] args) throws Exception {
String path = "E:\\PropetiesUtil\\test.properties";
PropertiesUtil pro = new PropertiesUtil(path);
pro.setProperties("test", "测试测试");
pro.setProperties("must", "1");
pro.setProperties("hehe", "it's so simple");
pro.save();
System.out.println(pro.getProperties("test"));
pro = null;
}
}
一个处理多语言自定义国际化的类, 也用来处理 porperties 文件
如果自己写一个多语言的应用程序,自己在应用程序总定义了如下几个国际化的文件:
1.application_zh_CN.properties
2.application_cn.properties
要的到文件里面国际化的内容也有通用的方法,当然,你可以采用上面的方法,一个更简单的方法如下:
package com.yihaomen.util;
import java.text.MessageFormat;
import java.util.Locale;
import java.util.ResourceBundle;
public class ResourcesUtil {
/**
* 通过Key获取对应的统一资源文件中的描述信息
*
* @param args
* 参数输入顺序:第一个参数为key,从第二个往后对应为Resource文件中的{0}、{1}、{2}
* @return String
*/
public static String getText(Object... args) {
if (args == null || args.length == 0) {
throw new RuntimeException(
"bad parameters of ResourceUtil.getText.");
}
String key = args[0].toString();
Locale locale = null;
String bundleName = null;
//国际化的文件放在这个package 下面.
bundleName = "com.yihaomen.ApplicationResources";
locale = Locale.SIMPLIFIED_CHINESE;
ResourceBundle rb = ResourceBundle.getBundle(bundleName, locale);
String msg = rb.getString(key);
if (msg == null) {
throw new RuntimeException("bundle key not found:" + key);
}
Object[] fmargs = new Object[args.length - 1];
if (fmargs.length == 0) {
return msg;
}
for (int i = 0; i < fmargs.length; i++) {
fmargs[i] = args[i + 1];
}
return MessageFormat.format(msg, fmargs);
}
}
这是常用来处理properties 文件的两个工具类,可以直接在项目中使用,也还有别的方法,与 properties 相关的操作方法,还可以参考这里:
Propeties文件与stream 之间的转换
From:一号门
Previous:网站打算进驻阿里云,申请备案中, 无奈关站一个月

COMMENTS