我想写一个算法将任意文件路径转换为规范形式(即删除任何"。"和" .."其中"。&#34 ;表示"当前目录"和" .."表示"向上一级")。我已经删除了"。"没错,那部分很容易。
例如:
/web/foo/bar/../baz/../../blat/./../foobie/bletch.html
应该成为
/web/foobie/bletch.html
和
www/someDir/./index.html
应该成为
www/someDir/index.html
和
www/someDir/./index.html
应该成为
www/index.html
到目前为止,这是我的代码:
public static String makeCanonical(String uri) {
String canonical="";
System.out.println("+" + uri); //for testing, doesn't need to print
ArrayList<String> parts=new ArrayList<String>();
int currentIndex=0;
//split string at every '/' into an ArrayList substring
for(int i=0; i<uri.length(); i++){
if(uri.charAt(i)=='/'){
parts.add(uri.substring(currentIndex, i+1));
currentIndex=i+1;
}
}
//trying to go up one level at every '..' ; not working correctly
for(int i=0; i<parts.size(); i++){
if(parts.get(i).contains("..")){
parts.remove(i);
parts.remove(i-1);
}
}
//compile all parts into single string
for(int i=0; i<parts.size(); i++){
canonical=canonical+parts.get(i);
}
//discard and '.' (single dot) characters
canonical=canonical.replaceAll("/./", "/");
if(canonical.contains(".")){
}
System.out.print("-" + canonical); //printing for testing
System.out.println();
System.out.println();
return canonical;
}
这是我的输出格式
+(original)
-(output)
-
+www/index.html
-www/
+/web/foo/bar/../baz/../../blat/./../foobie/bletch.html
-/web/foo/baz/blat/foobie/
+www/someDir/
-www/someDir/
+www/someDir/anotherDir/../../index.html
-www/someDir/../