struts2中取得文件的绝对路径的方法

方法1:

  1. ServletActionContext.getServletContext().getRealPath(File.separator);//项目根路径如D:\xxx\项目名
 ServletActionContext.getServletContext().getRealPath(File.separator);//项目根路径如D:\xxx\项目名

这个方法如果在action的一般方法中执行没问题可得到,但是放到static初始化中时就会报错:

  1. privatestatic String basePath;
  2. static {
  3. basePath = ServletActionContext.getServletContext().getRealPath(File.separator);
  4. }
private static String basePath;
static {
	basePath = ServletActionContext.getServletContext().getRealPath(File.separator);

}

具体为什么没有研究出来

方法2:

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

得到的字符串是形如:

D:/Java/Tomcat%206.0/webapps/项目名/WEB-INF/classes

而且如果路径中包含空格的话会显示为“%20”,要替换截取得到想要的路径如:

  1. basePath = ProductStage.class.getClassLoader().getResource("")
  2. .getFile().replaceAll("/WEB-INF/classes/", "").replaceAll("%20", " ").substring(1);
basePath = ProductStage.class.getClassLoader().getResource("")
   .getFile().replaceAll("/WEB-INF/classes/", "").replaceAll("%20", " ").substring(1);

猜你喜欢

转载自wanxiaotao12-126-com.iteye.com/blog/1949561