java获取文件所在服务器位置路径

1、通过 import javax.servlet.ServletContext 类获取web 服务器所在真实路径

    public ActionForward execute( ActionMapping mapping,   
            ActionForm actionform,   
            HttpServletRequest request,   
            HttpServletResponse response )   
            throws IOException, ServletException   
    {   
        HttpSession session = request.getSession();     
        ServletContext
  application  = session.getServletContext();   
       // ServletContext  application = servlet.getServletContext();       
      
        String Path = application.getRealPath 
("/")   
                      +"myDoc/ContributesBoxAtt/"+bean.getAttRealName();      
        Path = Path.replace("/", File.separator);      
      
        return mapping.findForward("");   
    }  
 

 

 

 

2、 获取类文件中获取文件所在的真实路径

   java  代码

  比如获取存放在 WEB-INF/classes/ 下的 title.xml 的路径

String path = this.getClass().getResource("/").getPath();      
//String path1= this.getClass().getClassLoader().getResource("/").getPath();    
int lastNum = path.lastIndexOf("/classes/");   
path = path.substring(0,lastNum)+"/title.xml";    

 

 

输出 :  D:/WORK/HDOA/build/web/WEB-INF/classes/title.xml

 

你可能感兴趣的:(java,Web,xml,bean,servlet)