I want to write an algorithm to convert an arbitrary filepath to canonical form (i.e. remove any "." and ".." where "." means "current directory", and ".." means "up one level"). I've removed the "." correctly, that part's easy.
For example:
/web/foo/bar/../baz/../../blat/./../foobie/bletch.html
should become
/web/foobie/bletch.html
and
www/someDir/./index.html
should become
www/someDir/index.html
and
www/someDir/./index.html
should become
www/index.html
This is my code so far:
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;
}
This is my output in the form
+(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/../