类加载器读取配置文件
一共有常用四种方法
1 任意的类名.class.getResourceAsStream("/文件所在位置")
2 任意类名.class.getClassLoader().getResourceAsStream(“文件所在的位置”);
3 任意类名.class.getClassLoader().getResource("文件所在的位置’).openStream()
4 任意类名.class.getClassLoader().getResource("文件所在的位置’).openConnection().getInputStream()
注意文件所在的位置都是从包名开始写
例子:
文件目录结构:
jdbc2里面内容为
content = jdbc2222222222
jdbc.properties内容为
content = jdbc0000000000
public class TestProperties {
public static void main(String[] args) throws Exception {
//首先创建Porperties
Properties pro = new Properties();
//方法1
InputStream inStream = TestProperties.class.getResourceAsStream("/com/tyut/IO/jdbc2.properties");
//把输入流加入到pro当中
pro.load(inStream);
System.out.println(pro.get("content"));
//方法2
InputStream inStream2 = TestProperties.class.getClassLoader().getResourceAsStream("com/tyut/MyJDBC/jdbc.properties");
pro.load(inStream2);
System.out.println(pro.get("content"));
//方法3
InputStream inStream3 = TestProperties.class.getClassLoader().getResource("com/tyut/MyJDBC/jdbc.properties").openStream();
pro.load(inStream3);
System.out.println(pro.get("content"));
//方法四
InputStream inStream4 = TestProperties.class.getClassLoader().getResource("com/tyut/MyJDBC/jdbc.properties").openConnection().getInputStream();
pro.load(inStream4);
System.out.println(pro.get("content"));
}
}
运行结果: