2018.05.02servlet错误记录

private static Properties pp=null;//读配置文件
	private static FileInputStream fis=null;
	static{//只需要加载一次,所以放在静态代码块里
		try {
			//从dbinfo.properties中读取配置信息
			String path = Thread.currentThread().getContextClassLoader().getResource("dbinfo.properties").getPath();
		    fis = new FileInputStream(path);
			pp=new Properties();
			pp.load(fis);
			url=pp.getProperty("url");
			username=pp.getProperty("username");
			driver=pp.getProperty("driver");
			password=pp.getProperty("password");
			Class.forName(driver);

读取propertites配置文件,出现“系统找不到指定的文件”

通过上面的语句进行正确加载,同时dbinfo.properties文件要放在src目录下

这涉及到一个Tomcat主目录的问题,Tomcat的主目录默认是在bin目录下,如果使用

fis=new FileInputStream("dbinfo.properties");
pp.load(fis)

来加载文件,则需要把这个properties文件放在bin目录下才可以

当我们使用java web的时候,读取文件需要使用类加载器,因为类加载器的去读取资源的时候默认路径是src

private static Properties pp=null;//读配置文件
	private static FileInputStream fis=null;
	private static InputStream in=null;
	static{//只需要加载一次,所以放在静态代码块中
		try {
			//从dbinfo.properties中读取配置信息
			//String path = Thread.currentThread().getContextClassLoader().getResource("dbinfo.properties").getPath();
			//fis = new FileInputStream(path);
			//当我们使用java web的时候,读取文件需要使用类加载器
			in=SqlHelper.class.getClassLoader().getResourceAsStream("dbinfo.properties");
			pp=new Properties();
			pp.load(in);
			url=pp.getProperty("url");
			username=pp.getProperty("username");
			driver=pp.getProperty("driver");
			password=pp.getProperty("password");
			Class.forName(driver);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally {
			try {
				//fis.close();
				in.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			in=null;
		}
		


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值