类加载器读取配置文件
一共有常用四种方法
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"));
}
}
运行结果:

本文详细介绍了在Java中使用类加载器读取配置文件的四种常见方法,包括通过类的getResourceAsStream、getClassLoader().getResourceAsStream、getClassLoader().getResource().openStream以及getClassLoader().getResource().openConnection().getInputStream。通过示例代码展示了如何从不同路径读取jdbc.properties文件并加载其内容。
9653

被折叠的 条评论
为什么被折叠?



