这里只是举个例子,在读取配置文件时,可以这么使用。
public class BaseDao {
private static Properties dbConfig = new Properties();
static {
UpdateConfig();
}
public static void UpdateConfig(){
try {
//这个方式是通过类转载器去读,类转载器有个特殊性,只会装载一次,所以下面的文件一但被装载到内存中,就不能随着配置修改二改变。必须重新运行一次程序。
//InputStream in = BaseDao.class.getClassLoader().getResourceAsStream("/db.properties");
//这种方式只会装载文件的路径,而不会装载文件的内容,所有推荐使用。
String realPath = BaseDao.class.getClassLoader().getResource("/db.properties").getPath();
FileInputStream in = new FileInputStream(realPath);
dbConfig.load(in);
} catch (IOException e) {
e.printStackTrace();
}
}
public String getUrl(){
return dbConfig.getProperty("url");
}
}