zoukankan      html  css  js  c++  java
  • 写一个函数怎么把相对路径转化为绝对路径(还是绝对路径转化为相对路径)?

    问题描述: 写一个函数怎么把相对路径转化为绝对路径(还是绝对路径转化为相对路径)?

    问题分析: 这里面的绝对路径可以是网络上的链接路径,也可以是本地绝对路径。

                 例如:strWeb = "http://456.e.now.cn/";
                        innerURL = "../share/style.css";

                        拼接后的绝对路径为:http://456.e.now.cn/share/style.css

                 再例如:

                        strLocal = "C:/Users/lenovo/Desktop/";

                        innerURL="../share/style.css";

                        拼接后的路径为:C:/Users/lenovo/Desktop/share/style.css

         

                下面我们将分别写代码来实现:

    代码实现:  

             1、如果在web请求中出现这个问题的话,这个比较简单:

                 String   strRealPath   =   getServletContext().getRealPath(String   strVirtualPath);  

             2、在非web请求中,我们可以这样做:    

     

    package com.yonyou.test;
    
    import java.net.MalformedURLException;
    import java.net.URI;
    import java.net.URISyntaxException;
    import java.net.URL;
    
    
    
    
    
    /**
     * 测试类
     * @author 小浩
     * @创建日期 2015-4-18
     */
    public class Test{
    	public static void main(String[] args) throws MalformedURLException, URISyntaxException{
    		new Test().test();
    }
    
    /**
     * @throws URISyntaxException
     * @throws MalformedURLException
     */
    public void test() throws URISyntaxException, MalformedURLException{
      //1、获取网络上面的绝对URL
      URI base=new URI("http://456.e.now.cn/test/");//基本网页URI
      URI abs=base.resolve("../share/style.css");//解析于上述网页的相对URL,得到绝对URI
      URL absURL=abs.toURL();//转成URL
      System.out.println("网络上面的URL的绝对路径为:"+absURL);
      //2、获取本地的绝对URL
      String absURL2=System.getProperty("user.dir")+
    		                    "../share/style.css".substring(2, "../share/style.css".length());
      String absURL3=System.getProperty("user.dir")+"/"+
              "../../share/style.css".replaceAll("\.\./","");  //此处需要把"../"转义为"\.\./"
      System.out.println("本地的绝对路径为:"+absURL2);
      System.out.println("本地的绝对路径为:"+absURL3);
    	}}

      

      

     

          

  • 相关阅读:
    Quit Procrastinating! 20 Ways to Energize Out of Your Slump
    [转]会让你人生失败的31种原因
    Control Panel Applets
    MemTest
    The server at www.abstractspoon.com is taking too long to respond.
    拖延者 <<拖延心理学>>
    [转]How to Uninstall Windows Movie Maker
    经典街机
    Causes and Cures for Procrastination
    给页面添加关键词和简介
  • 原文地址:https://www.cnblogs.com/xiohao/p/4437708.html
Copyright © 2011-2022 走看看