zoukankan      html  css  js  c++  java
  • Java相对路径/绝对路径总结(转)

    String path = Struts2Util.getServletContext().getRealPath("/");
    <%
      String path = request.getContextPath();
      String basePath = request.getScheme() + "://"
    			+ request.getServerName() + ":" + request.getServerPort()
    			+ path + "/";
    %>
    


    一、方法一
    (1)、request.getRealPath("/");//不推荐使用获取工程的根路径
    (2)、request.getRealPath(request.getRequestURI());//获取jsp的路径,这个方法比较好用,可以直接在servlet和jsp中使用
    (3)、request.getSession().getServletContext().getRealPath("/");//获取工程的根路径,这个方法比较好用,可以直接在servlet和jsp中使用
    (4)、类的绝对路径:Class.class.getClass().getResource("/").getPath()
    结果:/D:/TEST/WebRoot/WEB-INF/classes/pack/
    this.getClass().getClassLoader().getResource("").getPath();//获取工程classes下的路径,这个方法可以在任意jsp,servlet,java文件中使用,因为不管是jsp,servlet其实都是java程序,都是一个class。所以它应该是一个通用的方法。
    (5)、tomcat下获得绝对路径

    private String projectName="sz_pro"; //你项目的名称(File.separator)
    
    //获取当前项目的绝对路径(Linux不适用)
    public String getPorjectPath(){
      String nowpath; //当前tomcat的bin目录的路径 如 D:javasoftwareapache-tomcat-6.0.14in
      String tempdir;
      nowpath=System.getProperty("user.dir");
      tempdir=nowpath.replace("bin", "webapps"); //把bin 文件夹变到 webapps文件里面
      tempdir+= "\" + projectName;
      //判断是否有后缀
      if(!"/".equals(tempdir.substring(tempdir.length()))){
        tempdir += File.separator;
      }
      return tempdir;
    }
    



    //另外还有一个方法可以用来获取类的绝对路径(当前的classpath)windows,linux都可以

    String classesPath = this.getClass().getClassLoader().getResource("").getPath();
    logger.info("=============Constant.getPorjectPath()="+classesPath);
    String photoPath = Constant.getPorjectPath(classesPath) + "virtualdir/upload/data/photo/fmcg/";
    logger.info("=============photoPath="+photoPath);
    

     

     //获取当前项目的绝对路径   
        public static String getPorjectPath(String classesPath){   
          String tempdir;
          String classPath[] = classesPath.split("webapps");
          tempdir=classPath[0];
          if(!"/".equals(tempdir.substring(tempdir.length()))){
        	  tempdir += File.separator;
          }
          return tempdir;   
        }   
    


    (6)struts获得路径(struts2-core-2.0.11.2.jar)

    fileName = request.getParameter("FILENAME");
    SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd");
    SimpleDateFormat df1 = new SimpleDateFormat("yyyyMMddHHmmss");
    //获得项目中的根路径。如果项目删除照片也会失去
    File folder = new File(ServletActionContext.getServletContext().getRealPath("/")+"UploadImages/"+df.format(new Date()));
    if (!folder.exists()) {
      folder.mkdirs();
    }
    




    public String getPath(String uploadType,String loginId)
    {
    ActionContext ac = ActionContext.getContext();
    ServletContext sc = (ServletContext) ac.get(ServletActionContext.SERVLET_CONTEXT);
    String savePath = sc.getRealPath("/");
    String realPath = "webapps" + sc.getContextPath().replace("/", "\");
    String path = "virtualdir\upload\data\filezip\"+loginId+"\";
    if ("1".equals(uploadType)) {
    path = "virtualdir\upload\data\photozip\"+loginId+"\";
    }
    savePath = savePath.substring(0, savePath.length() - realPath.length() - 1) + path;
    return savePath;
    }
    


    二、方法二
    在jsp和class文件中调用的相对路径不同。 在jsp里,根目录是WebRoot 在class文件中,根目录是WebRoot/WEB-INF/classes 当然你也可以用System.getProperty("user.dir")获取你工程的绝对路径。

    另:在Jsp,Servlet,Java中详细获得路径的方法!

    1.jsp中取得路径:

    以工程名为TEST为例:

    (1)得到包含工程名的当前页面全路径:request.getRequestURI()
    结果:/TEST/test.jsp
    (2)得到工程名:request.getContextPath()
    结果:/TEST
    (3)得到当前页面所在目录下全名称:request.getServletPath()
    结果:如果页面在jsp目录下 /TEST/jsp/test.jsp
    (4)得到页面所在服务器的全路径:application.getRealPath("页面.jsp")
    结果:D:"resin"webapps"TEST"test.jsp
    (5)得到页面所在服务器的绝对路径:absPath=new java.io.File(application.getRealPath(request.getRequestURI())).getParent();
    结果:D:"resin"webapps"TEST

    2.在类中取得路径:

    (1)类的绝对路径:Class.class.getClass().getResource("/").getPath()
    结果:/D:/TEST/WebRoot/WEB-INF/classes/pack/
    (2)得到工程的路径:System.getProperty("user.dir")
    结果:D:"TEST

    3.在Servlet中取得路径:

    (1)得到工程目录:request.getSession().getServletContext().getRealPath("") 参数可具体到包名。
    结果:E:"Tomcat"webapps"TEST
    (2)得到IE地址栏地址:request.getRequestURL()
    结果:http://localhost:8080/TEST/test
    (3)得到相对地址:request.getRequestURI()
    结果:/TEST/test

    1.基本观点的理会

    对路径:绝对路径就是你的主页上的文件或目录在硬盘上真实的路径,(URL和物理路径)比方:

      C:xyz est.txt 代表了test.txt文件的绝对路径。http://www.sun.com/index.htm也代表了一个URL绝对路径。

      相对路径:相对与某个基准目录的路径。包含Web的相对路径(HTML中的相对目录),比方:在

      Servlet中,"/"代表Web使用的跟目录。和物理路径的相对示意。比方:"./" 代表当前目录,"../"代表上级目录。这种类似的示意,也是属于相对路径。

      另外关于URI,URL,URN等内容,请参考RFC有关文档规则。

      RFC 2396: Uniform Resource Identifiers (URI): Generic Syntax,

      (/ArtImage/20100102/rfc2396.txt)

    2.关于JSP/Servlet中的相对路径和绝对路径
    2.1服务器端的地址

      服务器端的相对地址指的是相对于你的web使用的地址,这个地址是在服务器端分析的(不一样于html和javascript中的相对地址,他们是由客户端阅读器分析的)也就是说这时刻在jsp和servlet中的相对地址应该是相对于你的web使用,即相对于http: //192.168.0.1/webapp/的。

      其用到的地点有:

      forward:servlet中的request.getRequestDispatcher(address);这个address是在服务器端分析的,所以,你要forward到a.jsp应该这么写:request.getRequestDispatcher(“/user/a.jsp”)这个/ 相对于当前的web使用 webapp,其绝对地址就是:http://192.168.0.1/webapp/user/a.jsp。 sendRedirect:在jsp中<%response.sendRedirect("/rtccp/user/a.jsp");%>

      2.2、客户端的地址

      所有的html页面中的相对地址都是相对于服务器根目录(http://192.168.0.1/)的,而不是(跟目录下的该Web使用的目录) http://192.168.0.1/webapp/的。 Html中的form表单的action属性的地址应该是相对于服务器根目录(http://192.168.0.1/)的,所以,假如提交到a.jsp 为:action="/webapp/user/a.jsp"或action="<%=request.getContextPath()% >"/user/a.jsp;

      提交到servlet为actiom="/webapp/handleservlet" Javascript也是在客户端分析的,所以其相对路径和form表单一样。

      因此,通常情况下,在JSP/HTML页面等引用的CSS,Javascript.Action等属性前面最好都加上

    <%=request.getContextPath()%>,以确保所引用的文件都属于Web使用中的目录。另外,应该尽量防止运用类似".","./","../../"等类似的相对该文件位置的相对路径,这样当文件移动时,很简单出疑问。
    3. JSP/Servlet中取得当前使用的相对路径和绝对路径
    3.1 JSP中取得当前使用的相对路径和绝对路径

      根目录所对应的绝对路径:request.getRequestURI()

      文件的绝对路径  :application.getRealPath(request.getRequestURI());

      当前web使用的绝对路径 :application.getRealPath("/");

      取得请求文件的上层目录:new File(application.getRealPath(request.getRequestURI())).getParent()

      3.2 Servlet中取得当前使用的相对路径和绝对路径

      根目录所对应的绝对路径:request.getServletPath();

      文件的绝对路径 :request.getSession().getServletContext().getRealPath

      (request.getRequestURI())

      当前web使用的绝对路径 :servletConfig.getServletContext().getRealPath("/");

      (ServletContext对象取得几种形式:

      javax.servlet.http.HttpSession.getServletContext()

      javax.servlet.jsp.PageContext.getServletContext()

      javax.servlet.ServletConfig.getServletContext()

      )

    4.java 的Class中取得相对路径,绝对路径的要领

    4.1单独的Java类中取得绝对路径

      根据java.io.File的Doc文挡,可知:

      默认情况下new File("/")代表的目录为:System.getProperty("user.dir")。

      一下程序取得执行类的当前路径

    package org.cheng.file;
    
      import java.io.File;
    
      public class FileTest {
    
      public static void main(String[] args) throws Exception {
    
      System.out.println(Thread.currentThread().getContextClassLoader().getResource(""));
    
      System.out.println(FileTest.class.getClassLoader().getResource(""));
    
     System.out.println(ClassLoader.getSystemResource(""));
    
      System.out.println(FileTest.class.getResource(""));
    
      System.out.println(FileTest.class.getResource("/"));
    
      //Class文件所在路径
    
      System.out.println(new File("/").getAbsolutePath());
    
      System.out.println(System.getProperty("user.dir"));
    
      }
    
      }
    4.2服务器中的Java类取得当前路径
    
      (1).Weblogic
    
      WebApplication的系统文件根目录是你的weblogic安装所在根目录。
    
      比方:假如你的weblogic安装在c:eaweblogic700.....
    
      那么,你的文件根路径就是c:.
    
      所以,有两种形式能够让你访问你的服务器端的文件:
    
      a.运用绝对路径:
    
      比如将你的参数文件放在c:yourconfigyourconf.properties,
    
      直接运用 new FileInputStream("yourconfig/yourconf.properties");
    
      b.运用相对路径:
    
      相对路径的根目录就是你的webapplication的根路径,即WEB-INF的上一级目录,将你的参数文件放
    
      在yourwebappyourconfigyourconf.properties,
    
      这样运用:
    
      new FileInputStream("./yourconfig/yourconf.properties");
    
      这两种形式均可,自身挑选。
    
      (2).Tomcat
    
      在类中输出System.getProperty("user.dir");显示的是%Tomcat_Home%/bin
    
      (3).Resin
    
      不是你的JSP放的相对路径,是JSP引擎执行这个JSP编译成SERVLET的路径为根.比如用新建文件法测试File f = new File("a.htm");
    
      这个a.htm在resin的安装目录下
    
      (4).如何 读相对路径哪?
    
      在Java文件中getResource或getResourceAsStream均可
    
      例:getClass().getResourceAsStream(filePath);//filePath能够是"/filename",这里的/代表web
    
      揭晓根路径下WEB-INF/classes
    
      默认运用该要领的路径是:WEB-INF/classes。已经在Tomcat中测试。
    
      议决上面内容的运用,能够处理在Web使用服务器端,移动文件,查找文件,复制、删除文件等操作,同时对服务器的相对地址,绝对地址观点更加清晰。
    
      建议参考URI,的RFC规则文挡。同时对Java.io.File. Java.net.URI.等内容明白透彻,对其他方面的理会能够更加深入和透彻。
    
    5. 
    在.properties中指定路径
    如common.properties中
    UPLOAD_PATH=../../virtualdir/upload
    LOCATION_ALARM_IMAGE=./../../resource/images/locationImage.gif
    LOCATION_LAST_ALARM_IMAGE=./../../resource/images/locationImage2.gif
    

     

    String thisUserpath = ""+ File.separator + "";
    
  • 相关阅读:
    MySQL高可用之MHA的搭建
    MySQL MGR 集群搭建(单主模式&多主模式)
    ansible-playbook定义变量与使用
    linux LVM逻辑卷管理
    Oracle 19C RAC 静默(silent)安装on RHEL7.x
    Python语言基础02-变量和运算
    Python之路,Day6
    Python 之路 Day5
    Python之路,Day4
    Python之路,Day3
  • 原文地址:https://www.cnblogs.com/chenning/p/4989653.html
Copyright © 2011-2022 走看看