項目經常會讀取一些配置文件, 因此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
工程包結構