您的位置:首页 > 其它

写一个函数,算出两个文件的相对路径的

2013-04-11 17:49 453 查看
今天需要做这个功能,网上搜了下,新浪有实现这个功能的面试题,用了递归算法,两行代码搞定:

public static void main(String[] args) throws Exception {

String pathA = "/a/b/c/d/g/m/1.txt";
String pathB = "/c/b/c/d/g/h/2.txt";
System.out.println(pathARelativePathBRecursion(pathA,pathB,""));
}

/**
* pathA相对于pathB的相对路径 递归算法:
*
* @param pathA
* @param pathB
* @param i
* @return
*/
public static String pathARelativePathBRecursion(String pathA,String pathB, String tempPath) {
if (pathA.startsWith(pathB))
return pathA.replaceFirst(pathB+"/",tempPath.substring(0,tempPath.length()-3));
else
return pathARelativePathBRecursion(pathA, pathB.substring(0, pathB.lastIndexOf("/")), "../" + tempPath);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: