struts2获取文件真实路径

CreateTime--2017年8月25日15:59:33

Author:Marydon

struts2获取文件真实路径

需要导入:

import java.io.FileNotFoundException;
import org.apache.struts2.ServletActionContext; 

方法封装

/**
 * 获取指定路径的实际路径(文件所在磁盘路径)
 * 
 * @param servletContext
 * @param path 相对于目录发布所在路径的路径
 * @return 文件真实路径
 * @throws FileNotFoundException
 */
public static String getRealPath(String path) throws FileNotFoundException {

    // Interpret location as relative to the web application root directory.
    if (!path.startsWith("/")) {
        path = "/" + path;
    }
    String realPath = ServletActionContext.getServletContext().getRealPath(path);
    if (realPath == null) {
        throw new FileNotFoundException("未找到文件:" + path);
    }
    return realPath;
}

举例:

  该文件所在的发布根目录

  该文件所在的发布根路径

  该文件的真实路径

 

原文地址:https://www.cnblogs.com/Marydon20170307/p/7428461.html