return true;
}
- /**
- * return relative path of <code>filePath</code> based <code>root</code>
- *
- * @param root base path
- * @param filePath file path
- *
- * @return relative path
- */
- public static
- String
- getRelativePath(
- final String root,
- final String filePath
- )
- {
- final String[] rootFragments = FilenameUtil.getCanonicalFragments( root );
- final String[] fileFragments = FilenameUtil.getCanonicalFragments( filePath );
-
- Assert.isTrue(
- rootFragments.length < fileFragments.length,
- "root must be ancestor[" + root + "] of path[" + filePath + "]"
- );
-
- for ( int i = 0, n = rootFragments.length ; i < n ; ++i )
- {
- Assert.isTrue( ObjectUtil.equals( rootFragments[i], fileFragments[i] ), i + "th [" + rootFragments[i] + "] != [" + fileFragments[i] + "]" );
- }
-
- final StringBuilder buffer = new StringBuilder();
-
- for ( int i = rootFragments.length, n = fileFragments.length ; i < n ; ++i )
- {
- if ( rootFragments.length < i )
- {
- buffer.append( SEPARATOR_DIRECTORY );
- }
- buffer.append( fileFragments[i] );
- }
-
- return buffer.toString();
- }
+ /**
+ * return relative path of <code>filePath</code> based <code>root</code>
+ *
+ * @param root absolute base path
+ * @param filePath absolute file path
+ *
+ * @return relative path
+ */
+ public static
+ String
+ getRelativePath(
+ final String root,
+ final String filePath
+ )
+ {
+ final String[] rootFragments = FilenameUtil.getCanonicalFragments( root );
+ final String[] fileFragments = FilenameUtil.getCanonicalFragments( filePath );
+ int nRoot = rootFragments.length;
+ int nFile = fileFragments.length;
+ final StringBuilder buffer = new StringBuilder();
-
+ int nLoop = (nRoot < nFile)
+ ? nRoot : nFile;
+
+ int nStartDiffer = nLoop;
+
+ for (int i=0;i<nLoop;i++) {
+ if (!ObjectUtil.equals(rootFragments[i], fileFragments[i])) {
+ nStartDiffer = i;
+ break;
+ }
+ }
+
+ for (int i = 0;i<nRoot-nStartDiffer;i++) {
+ if (buffer.length()>0) {
+ buffer.append( SEPARATOR_DIRECTORY );
+ }
+ buffer.append("..");
+ }
+
+ for (int i=nStartDiffer;i<fileFragments.length;i++) {
+ if (buffer.length()>0) {
+ buffer.append(SEPARATOR_DIRECTORY);
+ }
+ buffer.append(fileFragments[i]);
+ }
+
+ return buffer.toString();
+ }
/**
* Create canonical form for file path
*
}
else if ( "..".equals( fragment ) )
{
+ if (stack.isEmpty()) {
+ continue;
+ }
stack.pop();
}
else
);
}
}
-
+
+ /**
+ *
+ */
+ @Test
+ public void test_getRelativePath() {
+ String cwd = "/a/b/c/d";
+ String[][] test_list = {
+ //input expected
+ {"/a/b/c/d", ""},
+ {"/a/b/c/d/e", "e"},
+ {"/a/b/d/e/f", "../../d/e/f"},
+ {"/a/b/d", "../../d"},
+ {"/b/d/e", "../../../../b/d/e"}
+ };
+ for (int i = 0 ; i<test_list.length; i++) {
+ String[] test = test_list[i];
+
+ String actual = FilenameUtil.getRelativePath(cwd, test[0]);
+ String expected = test[1];
+
+ assertEquals(expected, actual);
+ }
+ }
}