JAVA中通过反射获取文件的绝对路径和以流的方式返回

JAVA中通过反射获取文件的绝对路径

  • (旧方法)FileReader reader = new FileReader(“src\reflection\Test.properties”);
    这种方式的路径缺点是:移植性差,在IDEA中默认的当前路径是project的根
    这个代码离开了IDEA,换到了其他地方,比如Linux系统,可能当前路径就不是
    project的根了,这时这个路径就无效了
  • src是类的根路径
  • 一种比较通用的一种路径。即使代码换位置了,这样编写仍然是通用的。
    注意:使用以下通用方式的前提是:这个文件必须在类路径下(src下)
		String path = Thread.currentThread().getContextClassLoader()
                .getResource("reflection\\Test.properties").getPath();
        //获取了文件的绝对路径
        ///C:/Users/Lucky777/IdeaProjects/study/out/production/study/reflection%5cTest.properties
        System.out.println(path);


        FileReader reader = new FileReader(path);
/*
解释:
            Thread.currentThread() 当前线程对象
            getContextClassLoader() 是 线程对象 的方法,可以获取当前线程的类加载器对象
            getResource() 【获取资源】这是类加载器的对象的方法,
                            当前线程的类加载器默认从类的根路径吓加载资源

*/

以流的方式返回

public class ReflectionTest06 {
    public static void main(String[] args) throws Exception{
//        //原来的方式
//        String path1 = Thread.currentThread().getContextClassLoader()
//                .getResource("src/reflection/Test.properties").getPath();
//        FileReader fileReader = new FileReader(path1);
        
        //直接以流的方式返回
        InputStream reader = Thread.currentThread().getContextClassLoader()
                .getResourceAsStream("src/reflection/Test.properties");
        //加载属性配置文件
        Properties pro = new Properties();
        pro.load(reader);
        System.out.println(pro.getProperty("MyClass"));

        //close
        reader.close();
    }
}

你可能感兴趣的:(零基础)