在平常的项目中,我们经常需要用到一些配置文件,而加载配置文件的方法都差不多,所以就写了一个
PropertiesUtils来加载配置文件
package com.chen.aq.utils;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.Properties;
public class PropertiesUtil {
private static Properties properties = null;
private static final String file = "/commons-config.properties";
static{
loadProperties();
}
/**
* 读取默认的配置文件信息,默认的配置文件为/WEB-INF/classes/commons-config.properties
* @return
*/
public static void loadProperties(){
StringBuilder sb = getBasePath().append(file);
InputStream input = null;
try {
input = new FileInputStream(sb.toString());
properties = new Properties();
properties.load(input);
} catch (FileNotFoundException e) {
System.err.println("找不到配置文件:" + file);
} catch (IOException e) {
System.err.println("读取配置文件时出错:" + file);
} finally {
try {
if (input != null) {
input.close();
}
} catch (Exception e) {
System.err.println("关闭配置文件:" + file + " 时出错!");
}
}
}
private static StringBuilder getBasePath(){
// StringBuilder sb = new StringBuilder(PropertiesUtil.class.getResource("").getPath().replace("%20", " "));
// if(sb.indexOf("classes")!=-1){
// sb.delete(sb.indexOf("classes"),sb.length());
// }
//
// sb.append("classes");
//class.getClassLoader().getResource() :names are relative to classpath,but
//class.getResource() : names are relative to the class's package
StringBuilder sb = new StringBuilder(PropertiesUtil.class.getClassLoader().getResource("").getPath().replace("%20", " "));
return sb;
}
/**
* 读取配置文件信息
*
* @param fileName 配置文件路径名称,配置文件路径为/WEB-INF/classes
* @return Properties
*/
public static Properties loadProperties(String fileName){
StringBuilder sb = getBasePath();
if(fileName!=null && fileName.startsWith("/")){
sb.append(fileName);
}else{
sb.append("/").append(fileName);
}
InputStream input = null;
try {
input = new FileInputStream(sb.toString());
Properties properties = new Properties();
properties.load(input);
return properties;
} catch (FileNotFoundException e) {
System.err.println("找不到配置文件:" + fileName);
} catch (IOException e) {
System.err.println("读取配置文件时出错:" + fileName);
} finally {
try {
if (input != null) {
input.close();
}
} catch (Exception e) {
System.err.println("关闭配置文件:" + fileName + " 时出错!");
}
}
return null;
}
public static void setPropertyToFile(String key, String value){
if(properties==null){
return;
}
properties.setProperty(key, value);
FileOutputStream out = null;
try {
URL resource = PropertiesUtil.class.getClassLoader().getResource(file);
out = new FileOutputStream(resource.getPath());
properties.store(out, null);
} catch (FileNotFoundException e) {
System.err.println("找不到配置文件:" + file);
} catch (IOException e) {
System.err.println("设置配置文件时出错:" + file);
} finally{
if(out!=null){
try {
out.close();
} catch (IOException e) {
System.err.println("关闭配置文件:" + file + " 时出错!");
}
}
}
}
}