一、属性文件加载类
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;
public class PropertiesUtils {
/**
* Load properties file from classpath.
*/
public static Properties loadPropertiesResource(String aResourcePath) throws IOException {
try {
ClassLoader classLoader = PropertiesUtils.class.getClassLoader();
Properties properties = new Properties();
// Try loading it.
properties.load(classLoader.getResourceAsStream(aResourcePath));
return properties;
} catch (Throwable t) {
throw new IOException("failed loading Properties resource from " + aResourcePath);
}
}
/**
* Load properties file from file path.
*/
static public Properties loadPropertiesFile(String aFilePath) throws IOException {
try {
Properties properties = new Properties();
properties.load(new FileInputStream(aFilePath));
return properties;
} catch (Throwable t) {
throw new IOException("failed loading Properties file from " + aFilePath);
}
}
/**
* Shorthand for current time.
*/
static public long now() {
return System.currentTimeMillis();
}
}
二、属性文件管理类
import java.io.File;
import java.util.Properties;
public class Config {
private static final String PROPERTIES_FILE = "config.properties";
private static Properties properties;
private Config() throws Exception{
throw new Exception("Config cant be init");
}
/**
* Initialize event sources from properties file.
*/
public static void load(String aDirPath) {
// Load Event sources using properties file.
try {
properties = PropertiesUtils.loadPropertiesResource(PROPERTIES_FILE);
} catch (Throwable t) {
String filePath = aDirPath + File.separator + PROPERTIES_FILE;
try {
properties = PropertiesUtils.loadPropertiesFile(filePath);
} catch (Throwable t2) {
return;
}
}
}
public static String getProperty(String aName, String aDefault) {
return properties.getProperty(aName, aDefault);
}
public static String getProperty(String aName) {
String value = properties.getProperty(aName);
if (value == null) {
throw new IllegalArgumentException("Unknown property: " + aName);
}
return value;
}
public static boolean getBoolProperty(String aName) {
String value = getProperty(aName);
try {
return value.equals("true");
} catch (Throwable t) {
throw new IllegalArgumentException("Illegal property value: " + aName + " val=" + value);
}
}
public static int getIntProperty(String aName) {
String value = getProperty(aName);
try {
return Integer.parseInt(value);
} catch (Throwable t) {
throw new IllegalArgumentException("Illegal property value: " + aName + " val=" + value);
}
}
public static long getLongProperty(String aName) {
String value = getProperty(aName);
try {
return Long.parseLong(value);
} catch (Throwable t) {
throw new IllegalArgumentException("Illegal property value: " + aName + " val=" + value);
}
}
public static boolean hasProperty(String aName) {
return properties.containsKey(aName);
}
}