javaweb程序中,普通的java类,不是servlet类读取资源文件的方式

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);
	}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值