private static String normalizePath ( final String path , final String separator ) { final String p = path . replace ( WINDOWS_SEPARATOR , separator ) . replace ( UNIX_SEPARATOR , separator ) ; // remove "." from the directory. final List < String > dirs = new LinkedList <> ( ) ; final StringTokenizer tokenizer = new StringTokenizer ( p , separator ) ; while ( tokenizer . hasMoreTokens ( ) ) { final String token = tokenizer . nextToken ( ) ; if ( ! ( "." . equals ( token ) ) ) { dirs . add ( token ) ; } } // remove ".." and the dir name before it. int dirNum = dirs . size ( ) ; int i = 0 ; while ( i < dirNum ) { if ( i > 0 ) { final String lastDir = dirs . get ( i - 1 ) ; final String dir = dirs . get ( i ) ; if ( ".." . equals ( dir ) && ! ( ".." . equals ( lastDir ) ) ) { dirs . remove ( i ) ; dirs . remove ( i - 1 ) ; dirNum = dirs . size ( ) ; i = i - 1 ; continue ; } } i ++ ; } // restore the directory. final StringBuilder buff = new StringBuilder ( p . length ( ) ) ; if ( p . startsWith ( separator + separator ) ) { buff . append ( separator ) . append ( separator ) ; } else if ( p . startsWith ( separator ) ) { buff . append ( separator ) ; } final Iterator < String > iter = dirs . iterator ( ) ; while ( iter . hasNext ( ) ) { buff . append ( iter . next ( ) ) ; if ( iter . hasNext ( ) ) { buff . append ( separator ) ; } } if ( p . endsWith ( separator ) ) { buff . append ( separator ) ; } return buff . toString ( ) ; }
Remove redundant names .. and . from the given path and replace directory separators .