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