读取资源文件时,因为已经将项目发布到服务器上了,所以要使用服务器路径来读取。
在业务逻辑中读取资源文件的两种方法
1,使用类加载器获取文件的路径,创建流读取。可以读取到实时数据。
public void save() throws Exception{
String path = UserDao.class.getClassLoader().getResource("/111.properties").getPath();
FileInputStream in = new FileInputStream(path);
Properties props = new Properties();
props.load(in);
System.out.println(props.getProperty("url"));
}
2,使用类加载器获取资源文件的 输入流,直接读取流中的信息。因为类只加载一次,读取到的信息都是初始化时的信息,不会随着资源文件更新而更新。
public void save1() throws Exception{
InputStream in = UserDao.class.getClassLoader().getResourceAsStream("/111.properties");
Properties props = new Properties();
props.load(in);
System.out.println(props.getProperty("url"));
}
servlet中读取配置文件
示例1:
private void test2() throws IOException{
ServletContext context = this.getServletContext();
InputStream in = context.getResourceAsStream("/WEB-INF/classes/com/dong/serveletDemo/jdbc.properties");
Properties props = new Properties();
props.load(in);
String url = props.getProperty("url");
String username = props.getProperty("username");
System.out.println(url);
System.out.println(username);
}
示例2:
//通过绝对路径来读取资源文件,优点:可以拿到文件名
private void readProps_2() throws IOException{
ServletContext context = this.getServletContext();
String path = context.getRealPath("/WEB-INF/classes/com/dong/serveletDemo/jdbc.properties");
System.out.println("文件名:" + path.substring(path.lastIndexOf("\\")+1 ));
FileInputStream in = new FileInputStream(path);
Properties props = new Properties();
props.load(in);
String url = props.getProperty("url");
String username = props.getProperty("username");
System.out.println(url);
System.out.println(username);
}
如果不在servlet中读取资源文件,需要使用类装载器进行读取资源文件,这时文件不能太大,资源文件太大,会导致内存溢出。