欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

java讀取資源路徑的幾種實(shí)現(xiàn)方式

 更新時(shí)間:2025年02月13日 08:49:37   作者:worilb  
文章總結(jié)了Java讀取資源路徑的幾種方式,并指出了在JUnit測(cè)試文件和普通類中讀取資源路徑的區(qū)別,普通類中讀取資源路徑時(shí),只返回主目錄,而JUnit測(cè)試文件中可以精確到所在模塊

java讀取資源路徑幾種方式

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

        String path = ClassUtils.getDefaultClassLoader().getResource("").getPath();
        System.out.println("類加載器返回默認(rèn)路徑:"+path);
        String path1 = ResourceUtils.getURL("classpath:").getPath();
        System.out.println("ResourceUtils返回默認(rèn)路徑:"+path1);
        String resourcePath = Thread.currentThread().getContextClassLoader().getResource("").getPath();
        System.out.println("resourcePath返回默認(rèn)路徑:"+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測(cè)試文件中的結(jié)果

工作可以精確到所在模塊,而普通類里打印是只有主目錄沒(méi)有模塊的。

如下:

  public static void main(String[] args) throws IOException {
        System.out.println("用戶當(dāng)前工作目錄"+System.getProperty("user.dir"));

        File directory = new File("");
        String path2 = directory.getCanonicalPath();
        System.out.println("當(dāng)前工作目錄1:"+path2);
        String path3 = directory.getAbsolutePath();
        System.out.println("當(dāng)前工作目錄2:"+path3);


    }

總結(jié)

以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。

相關(guān)文章

最新評(píng)論