在我们编写程序时都需要加一些配置文件来减少程序的改动,因此楼主写了一个工具类与大家分享
大家可以在程序启动时把所有的额配置文件加载到内存中来减少加载时间,就看大家的需求,自由发挥,废话不说直接贴代码
import java.io.File;
import java.io.FileInputStream;import java.io.FileNotFoundException;
import java.io.FilenameFilter;
import java.io.IOException;
import java.util.Enumeration;
import java.util.Properties;
import java.util.StringTokenizer;
public final class CfgToolbox
{
/**
* 加载多个.properties配置文件
* @param path
* @return
* @throws IOException
*/
public static final Properties loadAllProperties(String path)
throws IOException{
Properties result = new Properties();
File file = new File(path);
File[] files = file.listFiles();
for (int i = 0; i < files.length; i++) {
if(files[i].getName().endsWith(".properties")){
loadProperties(result, files[i]);
}
}
return result;
}
/**
* 把配置文件里的内容加载到Properties对象中
* @param props
* @param file
* @throws FileNotFoundException
* @throws IOException
*/
public static final void loadProperties(Properties props, File file) throws FileNotFoundException, IOException {
FileInputStream fis = new FileInputStream(file);
props.load(fis);
fis.close();
}
/**
* 把Properties里的key全部转化成小写
* @param props
* @return
*/
public static final Properties propertiesToLowerCase(Properties props) {
Properties result = new Properties();
Enumeration en = props.keys();
while (en.hasMoreElements()) {
String key = (String)en.nextElement();
String value = props.getProperty(key);
result.setProperty(key.toLowerCase(), value);
}
return result;
}
public static final String[] stringToArrayOfStrings(String data) {
StringTokenizer st = new StringTokenizer(data, ", ");
String[] result = new String[st.countTokens()];
for (int i = 0; i < result.length; i++) {
result[i] = st.nextToken();
}
return result;
}
public static void main(String[] args) {
try {
Properties properties =loadAllProperties("D:/data/logs/FrontServer");
System.out.println(properties.getProperty("url"));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}