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