这里只是举个例子,在读取配置文件时,可以这么使用。
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");
}
}
本文介绍了一种使用Java实现的配置文件加载方法,通过类加载器获取配置文件路径,并使用FileInputStream进行读取,确保了配置文件内容的正确加载。文章详细解释了两种不同方式的区别及其适用场景。
522

被折叠的 条评论
为什么被折叠?



