java读取资源路径的几种方式

在这里插入图片描述

    @Test
    public void path() throws IOException {
    
    
        System.out.println("用户当前工作目录"+System.getProperty("user.dir"));
        File directory = new File("");
        String path2 = directory.getCanonicalPath();
        System.out.println("当前工作目录1:"+path2);
        String path3 = directory.getAbsolutePath();
        System.out.println("当前工作目录2:"+path3);

        String path = ClassUtils.getDefaultClassLoader().getResource("").getPath();
        System.out.println("类加载器返回默认路径:"+path);
        String path1 = ResourceUtils.getURL("classpath:").getPath();
        System.out.println("ResourceUtils返回默认路径:"+path1);
        String resourcePath = Thread.currentThread().getContextClassLoader().getResource("").getPath();
        System.out.println("resourcePath返回默认路径:"+resourcePath);


        ClassPathResource classPathResource = new ClassPathResource("excel/xx.xlsx");
        System.out.println("ClassPathResource返回资源路径:"+classPathResource.getURL());
        URL resource = this.getClass().getClassLoader().getResource("excel/xx.xlsx");
        System.out.println("类加载器返回资源路径:"+resource.getPath());
        URL url = ResourceUtil.getResource("excel/xx.xlsx");
        System.out.println("ResourceUtil返回资源路径:"+url.getPath());


    }

在这里插入图片描述
注意,以上是在Junit测试文件中的结果,工作可以精确到所在模块,而普通类里打印是只有主目录没有模块的,如下:

  public static void main(String[] args) throws IOException {
    
    
        System.out.println("用户当前工作目录"+System.getProperty("user.dir"));

        File directory = new File("");
        String path2 = directory.getCanonicalPath();
        System.out.println("当前工作目录1:"+path2);
        String path3 = directory.getAbsolutePath();
        System.out.println("当前工作目录2:"+path3);


    }

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/worilb/article/details/131969286