resourcebundle
ResourceBundle与Properties的区别在于ResourceBundle通常是用于国际化的属性配置文件读取,Properties则是一般的属性配置文件读取。
ResourceBundle的单例使用如下
import java.util.ResourceBundle;
/**
* 访问配置文件 - 单例
* @author: cyq
* @since : 2015-09-30 10:17
*/
public class configuration {
private static ResourceBundle rb = null;
private volatile static Configuration instance = null;
private Configuration(String configFile) {
rb = ResourceBundle.getBundle(configFile);
}
public static Configuration getInstance(String configFile) {
if(instance == null) {
synchronized(Configuration.class) {
if(instance == null) {
instance = new Configuration(configFile);
}
}
}
return instance;
}
public String getValue(String key) {
return (rb.getString(key));
}
}
Properties的使用
import java.io.File;
import java.io.fileinputstream;
import java.io.Fileoutputstream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Enumeration;
import java.util.Properties;
public class PropertiesMain {
/**
* 根据Key读取Value
*
* @param filePath
* @param key
* @return
*/
public static String getValueByKey(String filePath, String key) {
Properties pps = new Properties();
InputStream in = null;
try {
// in = new BufferedInputStream(new FileInputStream(filePath));
in = PropertiesMain.class.getResourceAsStream(filePath);
pps.load(in);
String value = pps.getProperty(key);
System.out.println(key + " = " + value);
return value;
} catch (IOException e) {
e.printstacktrace();
return null;
}
}
/**
* 读取Properties的全部信息
*
* @param filePath
* @throws IOException
*/
public static void getAllProperties(String filePath) throws IOException {
Properties pps = new Properties();
InputStream in = PropertiesMain.class.getResourceAsStream(filePath);
pps.load(in);
Enumeration en = pps.propertyNames(); // 得到配置文件的名字
while (en.hasMoreElements()) {
String strKey = (String) en.nextElement();
String strValue = pps.getProperty(strKey);
System.out.println(strKey + "=" + strValue);
}
}
/**
* 写入Properties信息
*
* @param filePath
* @param pKey
* @param pValue
* @throws IOException
*/
public static void writeProperties(String filePath, String pKey,
String pValue) throws IOException {
Properties pps = new Properties();
InputStream in = new FileInputStream(filePath);
// 从输入流中读取属性列表(键和元素对)
pps.load(in);
OutputStream out = new FileOutputStream(filePath);
Object setProperty = pps.setProperty(pKey, pValue);
System.out.println(setProperty);
// 将此 Properties 表中的属性列表(键和元素对)写入输出流
pps.store(out, "Update " + pKey + " name");
}
public static void main(String[] args) throws IOException {
// 打印当前目录
// System.out.println(new File(".").getabsolutePath());
// 如果使用FileInputStream方式读取文件流 ./config/myconfig.properties
// 如果使用getResourceAsStream方式读取文件流 /myconfig.properties
// String value = getValueByKey("/myconfig.properties", "say.hello");
// System.out.println(value);
// getAllProperties("/myconfig.properties");
// writeProperties("./config/myconfig.properties","long", "2112");
}
}