getResourceAsStream用法

应用场景:

应用程序经常会使用到一些配置文件,例如如下数据库连接的配置文件 connect.txt文件

driver=org.postgresql.Driver
url=jdbc:postgresql://172.23.185.81:5435/student
uid=postgres
pwd=111

程序如何读取配置文件呢?

java中getResourceAsStream有以下定义

  • Finds a resource with a given name. The rules for searching resources associated with a given class are implemented by the defining class loader of the class. This method delegates to this object's class loader. 

结合Properties,可以很便捷的获取上述配置文件的读取和处理

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;


public class ResourceTest {

	private static String m_strClassDrive;   
	private static String m_strUrl;   
	private static String m_strUser;   
	private static String m_strPassword; 
	private final static String FILE_PATH_NAME = "/pointservice/connect.txt";
	
	public static void main(String[] args) {
		InputStream in = ResourceTest.class.getResourceAsStream(FILE_PATH_NAME);
		if (null == in) {
			System.out.println("文件获取失败!");
			return;
		}
		Properties props = new Properties();
		try {
			props.load(in);
			m_strClassDrive = props.getProperty("driver");
			m_strUrl = props.getProperty("url");
			m_strUser = props.getProperty("uid");
			m_strPassword = props.getProperty("pwd");
		} catch (IOException e) {
			e.printStackTrace();
		}
		System.out.println(m_strClassDrive);
		System.out.println(m_strUrl);
		System.out.println(m_strUser);
		System.out.println(m_strPassword);
	}
}

其中,注意将配置文件放在于程序的class文件下,以class文件作为根目录访问。



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值