@Test
public void testClass()
{
try {
Class class1 = Class.forName("com.object.Person");
System.out.println(class1.getPackage());
Object object =class1.newInstance();
System.out.println(object);
File file =new File("src/com/ClassTest/hello.txt");
OutputStream out =new FileOutputStream(file);
out.write(123);
out.close();
System.out.println();
Properties properties =new Properties();
InputStream inputStream = ClassTest.class.getClassLoader().
getResourceAsStream("com/ClassTest/hello.txt");//com/PropertiesTest/jdbc.properties
System.out.println(inputStream);
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
图中红色部分为测试代码,
File在创建文件时,是根据自身设定的路径决定的(Properties->Resource->location,为根目录),因此,文件若是想存放在其他子目录下,需要使用反斜杠;
然而,使用类加载器读取文件时,读取文件的路径为根目录下的src文件夹,(关系代码: ClassTest.class.getClassLoader()(此处也可以使用this.getClass/getClassLoader()代替))。
此处记下笔记。