package test.dao;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
/**
* 在web程序中,不再servlet中读取资源文件,只能通过类装载器方式
*
* 1.通过类加载器的方式读取资源文件,文件不能太大,因为读取文件的方式和读取类的方式一样, 太大了虚拟机会内存溢出
* 2.通过类加载器方式getResourceAsStream读取资源文件时,在程序运行中修改文件读取的还是原来的,因为类只装载一次!
* 解决这种方式请看方法updated2
*/
public class UserDao {
private static Properties dbconfig = new Properties();
// 通常这些连接数据库的资源配置只读取一遍,不在每个方法中单独读取
static {
// 拿到加载这个类的类加载器,也是加载所有类的类加载器,也可以加载资源文件
ClassLoader classLoader = UserDao.class.getClassLoader();
// 资源文件在src下,也就是web应用的WEB-INFO/classes下,类加载器的相对路径就是classes目录
InputStream in = classLoader.getResourceAsStream("db.properties");
// 模版方式读取文件
try {
dbconfig.load(in);
} catch (IOException e) {
e.printStackTrace();
}
}
public void update() throws IOException {
/*
* ClassLoader classLoader = UserDao.class.getClassLoader(); InputStream
* in = classLoader.getResourceAsStream("db.properties"); Properties
* dbconfig = new Properties(); dbconfig.load(in);
*/
String url = dbconfig.getProperty("url");
String username = dbconfig.getProperty("username");
String password = dbconfig.getProperty("password");
System.out.println(url);
System.out.println(username);
System.out.println(password);
}
// 因为通过类装载器的getResourceAsStream方法拿到流读取到的资源文件,改动后不会有效果,
// 想要看到实时效果需要先通过类装载器拿到资源路径,然后通过传统方式读取,而不是和加载类一样
public void update2() throws IOException {
String path = UserDao.class.getClassLoader()
.getResource("db.properties").getPath();
FileInputStream fis = new FileInputStream(path);
Properties prop = new Properties();
prop.load(fis);
String url = prop.getProperty("url");
String username = prop.getProperty("username");
String password = prop.getProperty("password");
System.out.println(url);
System.out.println(username);
System.out.println(password);
}
}
javaweb程序中,普通的java类,不是servlet类读取资源文件的方式
最新推荐文章于 2023-09-14 00:00:58 发布