淺談getResource方法


項目經常會讀取一些配置文件, 因此getResource方法便能夠起到重要作用

使用時主要是兩種方法, 一個是字節碼文件Class類, 另一個是ClassLoader類加載器

使用Class類時有兩種使用方式:

1. 使用"/"  獲取到的是classpath路徑

2. 不使用"/" 這就是相對路徑

ClassLoader類

沒有"/"的寫法, 獲取到的就是classpath路徑

測試代碼

public class GetResourceTest {

    public static void main(String[] args) {
        System.out.println(GetResourceTest.class.getResource("/test.properties").getPath());
        System.out.println(GetResourceTest.class.getResource("test1.properties").getPath());
        System.out.println(GetResourceTest.class.getClassLoader().getResource("test.properties").getPath());
        System.out.println(GetResourceTest.class.getClassLoader().getResource("/"));
    }

}

結果:

/E:/IdeaJava/studyTest/out/production/studyTest/test.properties
/E:/IdeaJava/studyTest/out/production/studyTest/com/waston/Test/test1.properties
/E:/IdeaJava/studyTest/out/production/studyTest/test.properties
null

工程包結構

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM