獲取web項目根目錄下的文件,讀取web項目根目錄下的某個文件


方法一:

String path =  this.getClass().getProtectionDomain().getCodeSource().getLocation().getPath();
path = path.substring(0,path.indexOf("/WEB-INF"));
String fileName =path+"/xxx.txt";
方法二:
這個就比較簡單了,直接看代碼:
BufferedReader br = new BufferedReader(new InputStreamReader(this.getClass().getResourceAsStream("/4_4.xml"),"utf-8"));
String s = "";
StringBuffer sb = new StringBuffer("");
while ((s = br.readLine()) != null) {
    sb.append(s + "\r\n");
}
br.close();

方法三:

inStream=DaoFactory.class.getClassLoader().getResourceAsStream("com/jdbc/dao/dao.properties");

第三種是最本質的做法,前兩種也是基於第三種去實現的。JVM會使用Bootstrap Loader去加載資源文件。所以路徑還是這種相對於工程的根目錄即"com/jdbc/dao/dao.properties"(不需要“/)

InputStream inStream = DaoFactory.class.getResourceAsStream("dao.properties"); --采用的相對路徑

inStream=DaoFactory.class.getResourceAsStream("/com/jdbc/dao/dao.properties") --采用絕對路徑,絕對路徑是相對於classpath根目錄的路徑


免責聲明!

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



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