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;
}

举例:

  该文件所在的发布根目录

  该文件所在的发布根路径

  该文件的真实路径

 

 

写在最后

  哪位大佬如若发现文章存在纰漏之处或需要补充更多内容,欢迎留言!!!

 相关推荐:

posted @ 2017-08-25 16:01  Marydon  阅读(1980)  评论(0编辑  收藏  举报