struts2中取得文件的絕對路徑的方法

方法1:java

ServletActionContext.getServletContext().getRealPath(File.separator);//項目根路徑如D:\xxx\項目名

這個方法若是在action的通常方法中執行沒問題可獲得,可是放到static初始化中時就會報錯:web

private static String basePath;
static {
	basePath = ServletActionContext.getServletContext().getRealPath(File.separator);

}

具體爲何沒有研究出來app

方法2:webapp

basePath = ProductStage.class.getClassLoader().getResource("")

獲得的字符串是形如:code

D:/Java/Tomcat%206.0/webapps/項目名/WEB-INF/classes字符串

並且若是路徑中包含空格的話會顯示爲「%20」,要替換截取獲得想要的路徑如:get

basePath = ProductStage.class.getClassLoader().getResource("")
   .getFile().replaceAll("/WEB-INF/classes/", "").replaceAll("%20", " ").substring(1);
相關文章
相關標籤/搜索