得到一個路徑相對另一個路徑的相對路徑

來源:互聯網
上載者:User

有點繞嘴,其實這個是為了下載帶圖片的網頁寫的一個函數。當把網頁和網頁連結的圖片都下載到本地時,一定要重定位網頁圖片的連結,否則下載到本地的圖片就沒有意義了。這個就是為了得到圖片的本地路徑相對連結它的網頁的本地路徑的相對路徑設計的。

 /**
     * <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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.