1.读取classpath下面任意文件(可以读取properties文件,也可以是任意其他类型的文件),废话 不多说,直接上代码:
// 读取classpath下面任意文件
URL url = ClassLoader.getSystemResource("one.properties");
// url.getFile() 得到这个文件的绝对路径 /D:/work/workspace/spring-datasource/target/classes/one.properties
InputStream inputStream = new FileInputStream(url.getPath());
Properties properties = new Properties();
properties.load(inputStream);
for (Map.Entry<Object, Object> objectObjectEntry : properties.entrySet()) {
System.out.println(objectObjectEntry.getKey() + ":" + objectObjectEntry.getValue());
}
System.out.println(ClassLoader.getSystemResourceAsStream("one.properties"));
ClassLoader classLoader = MyTest.class.getClassLoader();
System.out.println(classLoader.getResourceAsStream("one.properties"));
System.out.println(classLoader.getResource("one.properties"));
System.out.println(MyTest.class.getResource("/one.properties"));
System.out.println(MyTest.class.getResourceAsStream("/one.properties"));
执行效果如下:
2.读取一个package路径下面所有的class,代码如下:
List<Class> fromPackage = getClasssFromPackage("com.laozeng.test");
for (Class aClass : fromPackage) {
System.out.println(aClass.getName());
}
/**