Several ways for java to read resource paths

insert image description here

    @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());


    }

insert image description here
Note that the above is the result in the Junit test file, the work can be accurate to the module where it is located, and the print in the ordinary class is only the main directory without the module, as follows:

  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);


    }

insert image description here

Guess you like

Origin blog.csdn.net/worilb/article/details/131969286