public static String makeRelative ( String basePath , String targetPath ) { // Ensure the paths are both absolute or both relative. if ( isAbsolute ( basePath ) != isAbsolute ( targetPath ) ) { throw new IllegalArgumentException ( "Paths must both be relative or both absolute.\n" + " basePath: " + basePath + "\n" + " targetPath: " + targetPath ) ; } basePath = collapseDots ( basePath ) ; targetPath = collapseDots ( targetPath ) ; String [ ] baseFragments = basePath . split ( "/" ) ; String [ ] targetFragments = targetPath . split ( "/" ) ; int i = - 1 ; do { i += 1 ; if ( i == baseFragments . length && i == targetFragments . length ) { // Eg) base: /java/com/google // target: /java/com/google // result: . <-- . is better than "" since "" + "/path" = "/path" return "." ; } else if ( i == baseFragments . length ) { // Eg) base: /java/com/google // target: /java/com/google/c/ui // result: c/ui return Joiner . on ( "/" ) . join ( Lists . newArrayList ( Arrays . asList ( targetFragments ) . listIterator ( i ) ) ) ; } else if ( i == targetFragments . length ) { // Eg) base: /java/com/google/c/ui // target: /java/com/google // result: ../.. return Strings . repeat ( "../" , baseFragments . length - i - 1 ) + ".." ; } } while ( baseFragments [ i ] . equals ( targetFragments [ i ] ) ) ; // Eg) base: /java/com/google/c // target: /java/com/google/common/base // result: ../common/base return Strings . repeat ( "../" , baseFragments . length - i ) + Joiner . on ( "/" ) . join ( Lists . newArrayList ( Arrays . asList ( targetFragments ) . listIterator ( i ) ) ) ; }
Returns targetPath relative to basePath .