標籤:工程 運行時 out 資料 etc resource 另一個 方式 設定檔
轉自:https://www.cnblogs.com/wt20/p/8320346.html
項目經常會讀取一些設定檔, 因此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
工程包結構
以上為https://www.cnblogs.com/wt20/p/8320346.html博主所寫
最近在做項目時需要對資料庫的曆史資料進行處理,由於對oracle資料庫的定時任務不熟悉所以使用Java編寫了一個定時任務
在程式中需要讀取一個ctl檔案,但是,如果給定目錄的話,給客戶運行時可能由於檔案放在位置出錯而不能讀取到檔案,嘗試使用虛擬路徑,沒有成功,在網上搜到使用此方法可以擷取到目錄,嘗試使用,成功。
Java程式中讀取外部檔案時的路徑問題