得到一个路径相对另一个路径的相对路径

有点绕嘴,其实这个是为了下载带图片的网页写的一个函数。当把网页和网页链接的图片都下载到本地时,一定要重定位网页图片的链接,否则下载到本地的图片就没有意义了。这个就是为了得到图片的本地路径相对链接它的网页的本地路径的相对路径设计的。

 /**
     * <pre>得到一个路径相对另一个路径的相对路径</pre>
     * @version 2.0, 2006-09-5
     * @param strRootPath 根目录
     * @param strPath 工作目录
     * @return strPath相对strRootPath的相对路径
     * @author dl
     */
    public static String getPath(String strRootPath, String strPath) {
     File file = new File(strPath);
     File root = new File(strRootPath);
     ArrayList fileList = new ArrayList();
     ArrayList rootList = new ArrayList();
     File temp = file.getParentFile();
     
     fileList.add(file);
     while (temp != null) {
      fileList.add(temp);
      temp = temp.getParentFile();
     }
     rootList.add(root);
     temp = root.getParentFile();
     while (temp != null) {
      rootList.add(temp);
      temp = temp.getParentFile();
     }
     
     String strTemp1 = "";
     for (int i = 0; i < rootList.size(); ++i) {
      File fl1 = (File)rootList.get(i);
      String strTemp2 = "";
      for (int j = 0; j < fileList.size(); ++j) {
       File fl2 = (File)fileList.get(j);
       if (fl1.equals(fl2)) {
        if (strTemp1.length() != 0) {
         strTemp1 = strTemp1.substring(0, strTemp1.length() - 1);
        }
        return strTemp1 + strTemp2;
       }
       strTemp2 = "/" + fl2.getName() + strTemp2;
      }
      strTemp1 += "../";
     }
     
     return null;
    }

System.out.println(HtmlDown.getPath("C://Borland//JBuilder2005//thirdparty", "C://Documents and Settings//Administrator//My Documents//desktop_jpg//img_9_267_10.jpg"));

输出:  ../../../Documents and Settings/Administrator/My Documents/desktop_jpg/img_9_267_10.jpg

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值